流程控制

if-else 条件判断

程序根据条件走不同的路,就像你到了岔路口看路标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Test
public void testIfElse() {
int score = 85;

// 单条件
if (score >= 60) {
System.out.println("及格了");
}

// 双分支
if (score >= 90) {
System.out.println("优秀");
} else {
System.out.println("还需努力"); // ← 走这里
}

// 多分支
if (score >= 90) {
System.out.println("A - 优秀");
} else if (score >= 80) {
System.out.println("B - 良好"); // ← 走这里
} else if (score >= 60) {
System.out.println("C - 及格");
} else {
System.out.println("D - 不及格");
}
}

注意事项

if 后面的条件必须是 boolean 类型(参考 变量与数据类型 布尔章节)

Java不像C语言,不能用 if (1) 代替 if (true)

多分支从上往下匹配,匹配到第一个就停,不会继续往下走

只有一行时可以省略大括号,但不推荐

1
2
3
4
5
6
7
8
// ❌ 虽然语法合法,但容易出bug(以后加代码忘了补括号)
if (score >= 60)
System.out.println("及格");

// ✅ 养成好习惯,永远写大括号
if (score >= 60) {
System.out.println("及格");
}

简单的二选一可以用三元运算符替代(参考 运算符 三元运算符章节)

switch 分支选择

当你要拿一个值跟很多固定选项比较时,switch 比一堆 if-else 更清晰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Test
public void testSwitch() {
int day = 3;

// 传统 switch
switch (day) {
case 1:
System.out.println("周一");
break;
case 2:
System.out.println("周二");
break;
case 3:
System.out.println("周三"); // ← 走这里
break;
case 6:
case 7:
System.out.println("周末!"); // case 6 和 7 合并处理
break;
default:
System.out.println("周" + day);
break;
}
}

⚠️ break 不能忘!

如果忘了 break,会发生穿透(fall-through):匹配到之后的所有case都会执行

1
2
3
4
5
6
7
8
9
10
11
// ❌ 忘了break的后果
switch (day) {
case 1:
System.out.println("周一"); // 打印
// 没有break!继续往下走
case 2:
System.out.println("周二"); // 也打印了!
case 3:
System.out.println("周三"); // 也打印了!
}
// 如果 day=1,会打印"周一""周二""周三"三行

switch支持的类型

byteshortintchar — 基本整型

String — Java 7 开始支持

enum — 枚举类型

❌ 不支持 longfloatdoubleboolean

Java 14+ 新语法:switch表达式(了解)

1
2
3
4
5
6
7
8
9
// 新语法:箭头+不用写break,还能返回值
String result = switch (day) {
case 1 -> "周一";
case 2 -> "周二";
case 3 -> "周三";
case 6, 7 -> "周末";
default -> "周" + day;
};
System.out.println(result);

for 循环

知道要循环多少次时用 for,最最最常用的循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void testFor() {
// 基本for循环:从1打印到5
// for (初始化; 条件; 更新)
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
}
// 输出:1, 2, 3, 4, 5

// 执行顺序:
// 1. 初始化 i=1(只执行一次)
// 2. 判断 i<=5 → true → 执行循环体
// 3. i++(i变成2)
// 4. 判断 i<=5 → true → 执行循环体
// 5. ... 直到 i=6 时,i<=5 为 false,退出循环
}

常见用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 倒序循环
for (int i = 10; i >= 1; i--) {
System.out.println(i); // 10, 9, 8, ... 1
}

// 步长为2(只打印奇数)
for (int i = 1; i <= 10; i += 2) {
System.out.println(i); // 1, 3, 5, 7, 9
}

// 求1到100的和
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i; // 用到了 [运算符](/2026/04/04/运算符/) 中学的 +=
}
System.out.println("1到100的和 = " + sum); // 5050

嵌套循环

1
2
3
4
5
6
7
// 打印九九乘法表
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%d×%d=%-4d", j, i, i * j);
}
System.out.println();
}

增强for循环(for-each)

遍历数组或集合时更简洁,不需要下标

1
2
3
4
5
6
7
8
9
10
11
String[] fruits = {"苹果", "香蕉", "橙子"};

// 传统for
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}

// 增强for(推荐,更简洁)
for (String fruit : fruits) {
System.out.println(fruit);
}

缺点:拿不到下标 i,如果需要下标就用传统for

while 循环

不知道要循环多少次,只知道”什么时候停”时用 while

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void testWhile() {
// 基本 while:条件为true就一直循环
int count = 0;
while (count < 5) {
System.out.println("第" + count + "次");
count++;
}
// 输出:第0次, 第1次, 第2次, 第3次, 第4次

// 实战:读取数字的每一位(配合 取余与模运算)
int num = 12345;
System.out.print("逆序各位数:");
while (num > 0) {
System.out.print(num % 10 + " "); // 取个位
num /= 10; // 砍掉个位
}
// 输出:5 4 3 2 1
}

⚠️ 死循环

如果条件永远为true,循环永远不会停 → 程序卡死

1
2
3
4
5
6
// ❌ 忘了 count++,永远是 count=0 < 5,死循环!
int count = 0;
while (count < 5) {
System.out.println(count);
// 忘了 count++
}

故意的死循环(有时候需要)

1
2
3
4
5
6
// 服务器监听:一直等待请求,永不停止
while (true) {
// 等待连接...
// 处理请求...
// 永远运行,直到手动关闭
}

do-while 循环

和 while 的区别:先执行一次,再判断条件

保证循环体至少执行一次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void testDoWhile() {
// while:条件不满足一次都不执行
int x = 10;
while (x < 5) {
System.out.println("while: " + x); // 不会执行
}

// do-while:不管条件满不满足,至少执行一次
x = 10;
do {
System.out.println("do-while: " + x); // 会执行一次!
} while (x < 5);
}

典型场景:输入验证

1
2
3
4
5
6
7
8
// 一直让用户输入,直到输入合法为止
Scanner scanner = new Scanner(System.in);
int input;
do {
System.out.print("请输入1-100的数字:");
input = scanner.nextInt();
} while (input < 1 || input > 100);
// 至少会问一次,输入不合法就继续问

实际开发用得少,大多数场景 for 和 while 就够了

break 和 continue

break:立刻跳出整个循环

1
2
3
4
5
6
7
8
9
10
11
@Test
public void testBreak() {
// 找到第一个能被7整除的数就停下
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
System.out.println("找到了:" + i); // 7
break; // 找到了,不用继续了
}
}
System.out.println("循环结束");
}

continue:跳过本次,继续下一轮循环

1
2
3
4
5
6
7
8
9
10
@Test 
public void testContinue() {
// 打印1-10中的奇数(跳过偶数)
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 偶数跳过,直接进入下一次循环
}
System.out.println(i); // 1, 3, 5, 7, 9
}
}

break vs continue 对比

关键字 效果 比喻
break 直接离开循环 考试交卷走人
continue 跳过当前这一轮,继续下一轮 这道题不会,跳过做下一题

带标签的break(了解即可)

嵌套循环时,break默认只跳出最内层。想跳出外层循环需要加标签

1
2
3
4
5
6
7
8
9
10
// 在二维数组中找到目标值后跳出所有循环
outer: // ← 标签
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
System.out.println("找到了:i=" + i + " j=" + j);
break outer; // 直接跳出外层循环
}
}
}

for vs while vs do-while 怎么选?

场景 选择 例子
知道循环次数 for 遍历数组、1到100求和
不知道次数,只知道停止条件 while 读文件到末尾、等待用户输入
至少执行一次 do-while 输入验证、菜单选择
遍历集合/数组 for-each 遍历List、遍历String[]

实际开发中:for 用得最多(80%),while 其次(15%),do-while 很少用(5%)

综合练习

题1:打印1到100中所有的素数

素数:只能被1和自己整除的数(参考 计算机数学基础 密码学数学章节)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void testPrime() {
for (int n = 2; n <= 100; n++) {
boolean isPrime = true;
for (int i = 2; i * i <= n; i++) { // 只需要检查到√n
if (n % i == 0) {
isPrime = false;
break; // 发现因子,不是素数,提前退出
}
}
if (isPrime) {
System.out.print(n + " ");
}
}
// 输出:2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
}

题2:猜数字游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Test
public void testGuessNumber() {
int answer = (int)(Math.random() * 100) + 1; // 1~100随机数
Scanner scanner = new Scanner(System.in);
int guess;
int attempts = 0;

do {
System.out.print("猜一个1~100的数字:");
guess = scanner.nextInt();
attempts++;

if (guess > answer) {
System.out.println("大了");
} else if (guess < answer) {
System.out.println("小了");
}
} while (guess != answer);

System.out.println("恭喜猜对了!答案是" + answer + ",你猜了" + attempts + "次");
// 用二分法思路猜,最多7次就能猜到(参考 幂与对数 二分查找)
}

题3:FizzBuzz(经典面试题)

打印1到100,能被3整除打印Fizz,能被5整除打印Buzz,都能整除打印FizzBuzz

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void testFizzBuzz() {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}

上一章 目录 下一章
运算符 java基础 数组