第4章:控制流
本章只讲 Java。控制流是所有语言共通的概念,只是写法不同。
一个故事开头
你开了一家奶茶店。一天来了 100 个客人。
每个客人来,你都要做三件事:
- 判断:客人满 18 岁了才能买含酒精的饮品
- 选择:客人要热的还是冰的?
- 重复:100 个客人来了,同样的判断要做 100 次
程序也一样。前两章的程序是直来直去的——从上往下执行一遍,完事。但真实程序需要做选择(if)和做重复(for/while)。
这一章就讲这两件事。
1. if-else:做选择
最简单的 if
int age = 20;
if (age >= 18) {
System.out.println("已成年,可以购买");
}if 后面的括号里放条件表达式——结果是 true 就走花括号里的代码,是 false 就跳过。
💥 拆了它:试试条件为 false
int age = 15;
if (age >= 18) {
System.out.println("这行永远不会输出"); // ← 不会执行
}
System.out.println("这行肯定会输出"); // ← 会执行if-else:两条路
int score = 85;
if (score >= 60) {
System.out.println("及格了!");
} else {
System.out.println("没及格……");
}计算机要么走 if 分支,要么走 else 分支,不会都走。
if-else if-else:多条路
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}Java 从上往下检查条件,碰到第一个 true 就执行对应的分支,剩下的全跳过。
💥 拆了它:别犯 = 和 == 的错误
int x = 5;
if (x = 10) { // ❌ 编译错误!= 是赋值,不是判断
System.out.println("x 等于 10");
}正确的:if (x == 10)。
🧪 动手试试
写一个程序,输入一个数字,判断它是正数、负数还是零。用 if-else if-else。
int num = -3;
// 你的代码:
if (num > 0) {
System.out.println("正数");
} else if (num < 0) {
// ...
} else {
// ...
}2. switch:当有很多相等判断时
当你要判断一个变量等于不同的值分别做不同的事,用 switch 比一长串 if-else if 清爽得多。
int day = 3;
switch (day) {
case 1:
System.out.println("周一");
break;
case 2:
System.out.println("周二");
break;
case 3:
System.out.println("周三");
break;
case 4:
System.out.println("周四");
break;
case 5:
System.out.println("周五");
break;
default:
System.out.println("周末");
}⚠️ 别忘了 break
如果没有 break,执行完匹配的 case 之后会继续往下掉(这叫 fall-through):
int day = 3;
switch (day) {
case 3:
System.out.println("周三");
// 没有 break!
case 4:
System.out.println("周四也执行了");
}输出:
周三
周四也执行了有时候 fall-through 是有意的——比如多个 case 做同一件事:
switch (day) {
case 6:
case 7:
System.out.println("周末");
break;
default:
System.out.println("工作日");
}Java 14+ 的箭头语法
新写法,不用写 break,也没有 fall-through:
switch (day) {
case 1 -> System.out.println("周一");
case 2 -> System.out.println("周二");
case 3 -> System.out.println("周三");
case 4, 5 -> System.out.println("周四周五");
default -> System.out.println("周末");
}箭头语法还可以直接赋值:
String result = switch (score / 10) {
case 9, 10 -> "优秀";
case 8 -> "良好";
case 7 -> "中等";
case 6 -> "及格";
default -> "不及格";
};
System.out.println(result);3. for 循环:数着做重复
当你知道要重复多少次的时候,用 for 循环。
// 输出 5 次 "Hello"
for (int i = 0; i < 5; i++) {
System.out.println("Hello");
}拆开看 for 的四个部分:
for (①初始化; ②条件判断; ④步进操作) {
③循环体
}执行顺序:① → ②(条件为 true) → ③ → ④ → ② → ③ → ④ → ② → ... → ②(条件为 false) → 退出
// 逐步演示
for (int i = 0; i < 3; i++) {
System.out.println("第 " + i + " 次循环");
}
// 输出:
// 第 0 次循环 ← i=0, 0<3 true
// 第 1 次循环 ← i=1, 1<3 true
// 第 2 次循环 ← i=2, 2<3 true
// 结束 ← i=3, 3<3 false💥 拆了它:改条件看输出变化
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// 输出 1 2 3 4 5
// 改成 i < 5?
// 改成 i = 5?
// 改成 i += 2?遍历数组
int[] scores = {85, 90, 78, 92, 88};
for (int i = 0; i < scores.length; i++) {
System.out.println("第" + (i + 1) + "个成绩: " + scores[i]);
}4. while 循环:等到满足条件为止
当你不知道要重复多少次,只知道什么时候停,用 while。
int stock = 5;
while (stock > 0) {
System.out.println("卖出一杯,还剩 " + (stock - 1) + " 杯");
stock--;
}
System.out.println("卖完了!");while 和 for 的区别:
| for | while |
|---|---|
| 知道要循环多少次 | 不知道多少次,只知道什么时候停 |
| 遍历数组、固定次数的操作 | 等待用户输入、读文件到末尾 |
// while 的典型场景:等用户输入正确的密码
Scanner scanner = new Scanner(System.in);
String password = "";
while (!password.equals("123456")) {
System.out.print("请输入密码:");
password = scanner.nextLine();
}
System.out.println("密码正确!");5. do-while:至少执行一次
do-while 和 while 的唯一区别:先执行一次,再判断条件。
int x = 100;
do {
System.out.println("至少会执行一次");
x++;
} while (x < 10);
// 即使 x < 10 是 false,循环体也跑了一次💥 拆了它:对比 while 和 do-while
int x = 100;
while (x < 10) { // 条件一开始就是 false
System.out.println("不会执行");
}
do {
System.out.println("会执行一次"); // 先跑一遍再说
} while (x < 10);6. break 和 continue:控制循环节奏
// break:提前退出整个循环
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // i 等于 5 时跳出循环
}
System.out.print(i + " "); // 0 1 2 3 4
}// continue:跳过本次循环的剩余部分,进入下一次
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // 偶数跳过本次
}
System.out.print(i + " "); // 1 3 5 7 9
}🧪 动手试试
找出 1 到 100 之间所有能被 7 整除的数:
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
System.out.println(i);
}
}改成输出能被 3 和 5 同时整除的数(即 15 的倍数)。
7. 完整例子:奶茶店自动点单系统
public class MilkTeaOrderSystem {
public static void main(String[] args) {
// 菜单
String[] drinks = {"波波奶茶", "杨枝甘露", "柠檬茶", "抹茶拿铁"};
double[] prices = {15.0, 18.0, 12.0, 16.0};
System.out.println("===== 欢迎光临团子奶茶店 =====");
// 遍历菜单
for (int i = 0; i < drinks.length; i++) {
System.out.println((i + 1) + ". " + drinks[i] + " — " + prices[i] + "元");
}
// 模拟用户选择了第 3 号商品
int choice = 3; // 选柠檬茶
int quantity = 2;
// 判断商品编号是否有效
if (choice >= 1 && choice <= drinks.length) {
String selectedDrink = drinks[choice - 1];
double total = prices[choice - 1] * quantity;
System.out.println("已选择:" + selectedDrink + " × " + quantity);
System.out.println("总计:" + total + "元");
// 满减判断
if (total >= 30) {
System.out.println("满30减5!实付:" + (total - 5) + "元");
}
} else {
System.out.println("无效的商品编号");
}
// 等待结账(用 while 模拟)
double balance = 50.0;
while (balance >= total) {
System.out.println("余额充足,正在结账...");
break; // 实际应用里不是这么写的,这里为了演示
}
}
}我猜你会问
Q: = 和 == 到底有什么区别? A: = 是赋值——把右边的值放进左边的变量。== 是判断——比较左右两边是否相等。记住:单等号是动作,双等号是问题。
Q: for 和 while 什么时候用哪个? A: 有明确的计数就用 for("循环 N 次"、"遍历数组")。不固定次数就用 while("等用户输对"、"读文件直到结束")。
Q: switch 能判断 String 吗? A: 能。Java 7+ 的 switch 支持 String、int、char、enum 等。
String drink = "波波奶茶";
switch (drink) {
case "波波奶茶" -> System.out.println("15元");
case "杨枝甘露" -> System.out.println("18元");
default -> System.out.println("没有这个商品");
}你现在学会的东西
- if-else 做选择 — 从上往下检查,碰到第一个 true 就走
- switch 做多路分支 — 比一长串 if-else if 清爽,别忘了 break
- for 做固定次数的重复 — ①初始化 ②条件 ③循环体 ④步进
- while 做条件驱动的重复 — 不知道多少次,只知道什么时候停
- do-while — 至少执行一次
- break 跳出循环,continue 跳过本次
- 这三种结构组合起来,就能写任何程序了
✅ 验收标准
完成本章后,你应该能:
- [ ] 用
if-else实现二路分支 - [ ] 用
switch替代多重 if-else - [ ] 用
for和while实现循环 - [ ] 用
break提前退出循环 - [ ] 区分
for和while各自适合的场景
📌 常见卡点
- 忘记花括号——控制范围只有紧随的第一条语句
- switch 忘写 break——贯穿执行
- 无限循环——确保循环条件最终会变成 false
- else if 的缩进层级——嵌套过多时考虑 switch 或提取方法
🔜 现在不需要理解
- do-while 用得少,知道存在就行
- break label(带标签的 break)——几乎不用
- 增强 for 循环——学了数组/集合再用
🧪 练习
1. 写一个 if-else:声明 int score = 75,用 if-else 判断并输出"优秀"(>=90)、"良好"(>=80)、"及格"(>=60)、"不及格"(<60)。
2. for 循环:用 for 循环输出 1 到 20 之间所有能被 3 整除的数。
3. while 循环:用 while 循环模拟"反复猜密码"——声明 String password = "abc123",用一个计数器 int attempts = 0,每次 attempts 加 1,直到 attempts 达到 3 为止(提示:不用真的让用户输入,直接手动改 password 变量的值)。