条件控制:if / switch
程序不是永远从上到下顺序执行的。本节学习让程序"做判断"的两种语句:if 语句和 switch 语句。
一、if 语句的三种形式
1. 单分支 if
int score = 85;
if (score >= 60) {
System.out.println("及格了");
}
条件为 true 才执行大括号内的代码。
2. if-else 双分支
int score = 45;
if (score >= 60) {
System.out.println("及格了");
} else {
System.out.println("不及格,继续努力");
}
二选一,必走其一。
3. if-else if-else 多分支
int score = 92;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
从上往下逐个判断,一旦某个条件成立,后面的分支不再判断。
注意条件的书写顺序:范围判断要从小到大或从大到小排列,比如上面的 score >= 90 必须写在 score >= 80 前面,否则 92 分会被当成"良好"。
二、if 的常见坑
1. 大括号建议不要省略
if (score >= 60)
System.out.println("及格");
System.out.println("这是另一条语句"); // 注意:这行不在 if 里!
Java 允许 if 后面只跟一条语句,但这样极易写错。始终加花括号是良好习惯。
2. 判断相等要用 == 而不是 =
if (score = 60) { // 编译报错:int 不能转 boolean
= 是赋值,== 才是比较,写错会导致编译错误或逻辑错误。
3. 浮点数不要直接比较相等
double a = 0.1 + 0.2; // 实际是 0.30000000000000004
if (a == 0.3) { // false!
浮点数有精度误差,判断相等应该用差值小于一个极小值:
if (Math.abs(a – 0.3) < 0.000001) {
System.out.println("近似相等");
}
三、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;
default:
System.out.println("未知的日期");
break;
}
执行流程
穿透示例
int month = 7;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
System.out.println("31 天");
break;
case 4: case 6: case 9: case 11:
System.out.println("30 天");
break;
default:
System.out.println("2 月,28 或 29 天");
}
利用穿透特性,多个值共用一段逻辑,代码非常简洁。
支持的类型
switch 可以判断:byte、short、int、char、String(JDK 7+)、枚举。
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("苹果");
break;
case "banana":
System.out.println("香蕉");
break;
default:
System.out.println("不认识的水果");
}
现代写法:箭头表达式(JDK 14+)
JDK 14 起可以用 -> 写法,自动 break,不会穿透:
switch (day) {
case 1 -> System.out.println("星期一");
case 2 -> System.out.println("星期二");
default -> System.out.println("其他");
}
甚至可以作为表达式返回值(JDK 17 已稳定):
String name = switch (day) {
case 1 -> "星期一";
case 2 -> "星期二";
default -> "其他";
};
四、if 还是 switch?
- 判断范围、大小关系(分数、年龄)→ 用 if
- 判断固定值(星期几、菜单选项)→ 用 switch,代码更直观
五、综合练习
判断某年是平年还是闰年(能被 4 整除但不能被 100 整除,或能被 400 整除):
int year = 2024;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println(year + " 是闰年");
} else {
System.out.println(year + " 是平年");
}
六、小结
- if 适合范围判断,switch 适合固定值判断
- 每个 case 别忘了 break(或用 -> 写法)
- 判断相等用 ==,浮点数比较要小心精度
- 大括号始终加上,避免悬空 else 问题
下一节学习循环语句。
网硕互联帮助中心


评论前必须登录!
注册