Java 流程控制
程序的灵魂在于"做判断、能循环"。本章带你掌握 Java 的所有流程控制语句:if-else 条件分支、switch 多路分支、for/while 循环、break/continue 跳转。学完你能让程序处理任意复杂的逻辑。
1. if-else 条件分支
if-else 是最基础的条件判断,三种形式:单分支、双分支、多分支。
public class IfDemo {
public static void main(String[] args) {
int score = 75;
// 1. 单分支
if (score >= 60) {
System.out.println("及格了");
}
// 2. 双分支
if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
// 3. 多分支(注意顺序:从上往下,匹配一个就跳出)
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格"); // 命中这里
} else {
System.out.println("不及格");
}
}
}几个要点:
- 条件必须是
boolean,不能写if (x)(那不是 Java,是 C/JS),必须if (x != 0)。 else if从上往下匹配,命中一个就跳出,所以顺序很重要(把更严格的条件放前面)。- 代码块只有一行时可以省略
{,但强烈建议永远写(避免后续插入 bug)。
2. switch 多路分支(传统写法)
当条件是对一个值的多路判断时,switch 比 else if 更清晰。支持 int、char、String(Java 7+)、enum(Java 5+):
public class SwitchDemo {
public static void main(String[] args) {
int day = 3;
// 传统 switch(Java 5 起支持)
switch (day) {
case 1:
System.out.println("星期一");
break; // ⚠️ 忘了 break 会"穿透"到下一个 case!
case 2:
System.out.println("星期二");
break;
case 3:
System.out.println("星期三"); // 命中
break;
default: // 等同于 else
System.out.println("未知");
}
// 输出: 星期三
}
}最大的坑:忘写 break 会"穿透"——从匹配的 case 一直执行到 break 或结尾,可能把后面所有 case 都跑一遍。这种"穿透"偶尔有用(多个 case 共用代码),但绝大多数时候是 bug。
3. switch 表达式(Java 14+ 新语法)
Java 14 引入了更现代的 switch 表达式,用箭头 -> 代替冒号,不会穿透,还能直接返回值:
public class SwitchExpr {
public static void main(String[] args) {
int day = 3;
// Java 14+ switch 表达式:用 -> 不穿透,直接返回值
String name = switch (day) {
case 1 -> "星期一";
case 2 -> "星期二";
case 3 -> "星期三";
case 4, 5, 6, 7 -> "其他"; // 多个值合并
default -> "未知";
};
System.out.println(name); // 星期三
// 也可以用 yield 在代码块里返回值
int num = switch (day) {
case 1, 2, 3, 4, 5 -> {
System.out.println("工作日");
yield 1; // 用 yield 返回值
}
case 6, 7 -> 0;
default -> -1;
};
}
}这种写法避免了 break 忘写导致的 bug,可读性也大幅提升。新项目建议全部用 switch 表达式,只在维护老代码时用传统写法。
4. for 循环
Java 有两种 for:经典 for(知道循环次数时用)和增强 for / foreach(只遍历不关心索引时用)。
public class ForDemo {
public static void main(String[] args) {
// 1. 经典 for:初始化; 条件; 步进
for (int i = 0; i < 5; i++) {
System.out.print(i + " "); // 0 1 2 3 4
}
System.out.println();
// 2. 增强 for(foreach):遍历数组/集合,不能拿索引
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.print(n + " "); // 10 20 30
}
System.out.println();
// 3. 死循环(条件永远 true)
// for (;;) { ... } // 等价于 while (true),需要在内部 break
}
}- 知道次数用经典 for;只遍历数组/集合用 foreach;不知道次数用 while。
- foreach 的缺点是拿不到索引,需要修改元素或拿 index 时还是要用经典 for。
- 遍历时不能修改集合大小(add/remove),否则抛
ConcurrentModificationException,要删元素用Iterator。
5. while 和 do-while
public class WhileDemo {
public static void main(String[] args) {
// 1. while:先判断,可能一次都不执行
int i = 0;
while (i < 3) {
System.out.print(i + " "); // 0 1 2
i++;
}
System.out.println();
// 2. do-while:先执行一次,再判断(至少跑 1 次)
int j = 5;
do {
System.out.print(j + " "); // 5(即使条件不满足,也跑一次)
j++;
} while (j < 3);
// 实战:逐位剥离数字(求各位数字之和)
int n = 12345;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println("数字之和: " + sum); // 15
}
}while:先判断后执行,条件不成立可能一次都不跑。do-while:先执行一次再判断,至少跑 1 次。实际开发用得少,但某些场景(如菜单循环)很合适。- 死循环用
while (true),内部配合break跳出。
6. break 与 continue
public class BreakContinue {
public static void main(String[] args) {
// break:跳出整个循环
for (int i = 0; i < 10; i++) {
if (i == 5) break;
System.out.print(i + " "); // 0 1 2 3 4
}
System.out.println();
// continue:跳过本次,继续下一次
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue; // 跳过偶数
System.out.print(i + " "); // 1 3 5 7 9
}
System.out.println();
// 带标签的 break(跳出多层循环)
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) break outer; // 直接跳出外层
System.out.println(i + "," + j);
}
}
// 输出:
// 0,0 0,1 0,2 1,0 然后跳出
}
}break:跳出整个循环。continue:跳过本次,继续下一次。- 带标签的 break(
break outer;):一次性跳出多层嵌套循环,虽然语法偏冷门,但偶尔很有用。 - 在
switch里 break 是"跳出 switch",在循环里是"跳出循环",不要混淆。
7. 实战小例子:打印九九乘法表
用嵌套循环打印九九乘法表——这是经典的循环练习:
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%dx%d=%-4d", j, i, i * j);
}
System.out.println();
}
}
}
// 输出(部分):
// 1x1=1
// 1x2=2 2x2=4
// 1x3=3 2x3=6 3x3=9
// ...System.out.printf 是格式化输出(类似 C 的 printf),%-4d 表示左对齐、占 4 个字符宽的整数。
小结
这一章你掌握了 Java 的所有流程控制:if/else、switch、for、while、break/continue。新手记住三件事:switch 别忘 break(或用 Java 14 新语法)、foreach 不能改集合、拿不准加括号。下一篇我们看 Java 方法——把重复代码封装成可复用的"工具"。
← 上一篇 Java 运算符
下一篇 Java 方法 →