流程控制分两类:条件判断(if / switch)和循环(for / while / do-while)。
1. if 条件判断
if / else if / else
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class IfDemo { public static void main(String[] args) { int score = 75;
if (score >= 90) { System.out.println("优秀"); } else if (score >= 60) { System.out.println("及格"); } else { System.out.println("不及格"); } } }
|
要点:条件从上往下依次判断,命中一个就不再往下走;最后的 else 可省略。
2. switch 语句
适合「一个变量和多个固定值比较」的场景。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class SwitchDemo { public static void main(String[] args) { int day = 3;
switch (day) { case 1: System.out.println("星期一"); break; case 2: System.out.println("星期二"); break; case 3: System.out.println("星期三"); break; default: System.out.println("其他"); } } }
|
要点:
- 每个
case 结尾要写 break,否则会「贯穿」到下一个 case
default 在所有 case 都不匹配时执行,可省略
- switch 支持
int、char、String(JDK 7+)、枚举
贯穿(fall-through)示例:
1 2 3 4 5 6 7 8 9 10 11
| int month = 8; switch (month) { case 6: case 7: case 8: System.out.println("夏天"); break; default: System.out.println("其他季节"); }
|
3. for 循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class ForDemo { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println(i); }
int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; } System.out.println("1 到 100 的和 = " + sum); } }
|
for 三部分:初始化; 条件; 更新。
4. while 和 do-while
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class WhileDemo { public static void main(String[] args) { int i = 1; while (i <= 5) { System.out.println(i); i++; }
int j = 10; do { System.out.println("j = " + j); j++; } while (j <= 5); } }
|
5. 增强 for(foreach)
遍历数组、集合时更简洁。
1 2 3 4 5 6 7 8 9
| public class ForeachDemo { public static void main(String[] args) { int[] nums = {10, 20, 30, 40, 50};
for (int n : nums) { System.out.println(n); } } }
|
注意:foreach 只能读,不能修改数组元素(要用下标才能改)。
6. break 和 continue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class BreakContinueDemo { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { break; } System.out.print(i + " "); } System.out.println();
for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; } System.out.print(i + " "); } } }
|
7. 嵌套循环:九九乘法表
1 2 3 4 5 6 7 8 9 10
| public class NestedLoopDemo { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + "×" + i + "=" + (i * j) + "\t"); } System.out.println(); } } }
|
小结
- 判断:
if / else if / else 和 switch(记得 break)
- 循环:
for、while、do-while、增强 for
break 跳出整个循环,continue 跳过本次