Java入门到精通-06 流程控制之条件判断
·
目录
🔀 06 流程控制之条件判断
更新日期:2026年5月
版权声明:本文为原创文章,转载请注明出处。© 2026 Java入门到精通系列
一、什么是流程控制
1.1 程序的三种基本结构
任何复杂的程序都可以由三种基本结构组成:
┌─────────────────────────────────────────────────────────┐
│ 程序基本结构 │
├─────────────────┬─────────────────┬─────────────────────┤
│ 顺序结构 │ 选择结构 │ 循环结构 │
│ Sequential │ Selection │ Loop │
├─────────────────┼─────────────────┼─────────────────────┤
│ 从上到下依次执行 │ 根据条件选择执行 │ 重复执行某些代码 │
│ │ │ │
│ 语句1; │ if (条件) { │ while (条件) { │
│ 语句2; │ 语句A; │ 循环体; │
│ 语句3; │ } else { │ } │
│ │ 语句B; │ │
│ │ } │ │
└─────────────────┴─────────────────┴─────────────────────┘
1.2 条件判断的作用
条件判断让程序能够根据不同的情况做出不同的响应,是实现程序智能化的基础。
// 没有条件判断:只能顺序执行
System.out.println("今天是晴天");
System.out.println("出去玩");
// 有条件判断:可以根据情况做选择
if (天气 == "晴天") {
System.out.println("出去玩");
} else {
System.out.println("在家学习Java");
}
二、if语句
2.1 基本语法
if (条件表达式) {
// 条件为true时执行的代码
}
2.2 执行流程
┌───────────┐
│ 开始执行 │
└─────┬─────┘
│
┌─────▼─────┐
│ 判断条件 │
│ (条件表达式) │
└─────┬─────┘
true │ │ false
┌─────▼─────┐
│ 执行if代码块│ │
└─────┬─────┘ │
│◄─────────┘
┌─────▼─────┐
│ 继续执行 │
└───────────┘
2.3 代码示例
public class IfDemo {
public static void main(String[] args) {
// 示例1:判断是否成年
int age = 20;
if (age >= 18) {
System.out.println("你已成年,可以考驾照了!");
}
// 示例2:判断是否及格
int score = 55;
if (score >= 60) {
System.out.println("恭喜你,考试及格了!");
}
System.out.println("考试结束"); // 这行总会执行
// 示例3:条件表达式可以是复杂的逻辑
String username = "admin";
String password = "123456";
if ("admin".equals(username) && "123456".equals(password)) {
System.out.println("登录成功!");
}
}
}
三、if-else语句
3.1 基本语法
if (条件表达式) {
// 条件为true时执行
} else {
// 条件为false时执行
}
3.2 执行流程
┌───────────┐
│ 开始执行 │
└─────┬─────┘
│
┌─────▼─────┐
│ 判断条件 │
└─────┬─────┘
true │ │ false
┌─────────▼─┐ ┌─▼─────────┐
│执行if代码块│ │执行else代码块│
└─────────┬─┘ └─┬─────────┘
│◄────┘
┌─────▼─────┐
│ 继续执行 │
└───────────┘
3.3 代码示例
public class IfElseDemo {
public static void main(String[] args) {
// 示例1:判断奇偶数
int num = 7;
if (num % 2 == 0) {
System.out.println(num + "是偶数");
} else {
System.out.println(num + "是奇数");
}
// 示例2:判断是否成年
int age = 15;
if (age >= 18) {
System.out.println("已成年");
} else {
System.out.println("未成年");
}
// 示例3:求两个数的最大值
int a = 10, b = 20;
int max;
if (a > b) {
max = a;
} else {
max = b;
}
System.out.println("最大值:" + max);
// 简化写法:三元运算符
int max2 = (a > b) ? a : b;
System.out.println("最大值:" + max2);
}
}
四、if-else if-else语句
4.1 基本语法
if (条件1) {
// 条件1为true时执行
} else if (条件2) {
// 条件2为true时执行
} else if (条件3) {
// 条件3为true时执行
} else {
// 以上条件都不满足时执行
}
4.2 代码示例
public class IfElseIfDemo {
public static void main(String[] args) {
// 示例1:成绩等级判断
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 70) {
System.out.println("中等");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
// 示例2:BMI健康评估
double height = 1.75; // 身高(米)
double weight = 70; // 体重(千克)
double bmi = weight / (height * height);
System.out.println("BMI = " + String.format("%.1f", bmi));
if (bmi < 18.5) {
System.out.println("体重过轻");
} else if (bmi < 24) {
System.out.println("正常范围");
} else if (bmi < 28) {
System.out.println("超重");
} else {
System.out.println("肥胖");
}
// 示例3:星座查询(简化版)
int month = 5;
int day = 20;
String constellation;
if ((month == 3 && day >= 21) || (month == 4 && day <= 19)) {
constellation = "白羊座";
} else if ((month == 4 && day >= 20) || (month == 5 && day <= 20)) {
constellation = "金牛座";
} else if ((month == 5 && day >= 21) || (month == 6 && day <= 21)) {
constellation = "双子座";
} else {
constellation = "其他星座";
}
System.out.println("您的星座是:" + constellation);
}
}
五、嵌套if语句
5.1 基本语法
if (外层条件) {
if (内层条件) {
// 两个条件都满足
} else {
// 只满足外层条件
}
} else {
// 不满足外层条件
}
5.2 代码示例
public class NestedIfDemo {
public static void main(String[] args) {
// 示例1:判断一个数是否为正偶数
int num = 8;
if (num > 0) {
if (num % 2 == 0) {
System.out.println(num + "是正偶数");
} else {
System.out.println(num + "是正奇数");
}
} else if (num < 0) {
System.out.println(num + "是负数");
} else {
System.out.println("num是零");
}
// 示例2:用户登录验证
String username = "admin";
String password = "123456";
boolean isActive = true;
if ("admin".equals(username)) {
if ("123456".equals(password)) {
if (isActive) {
System.out.println("登录成功!");
} else {
System.out.println("账户已被禁用");
}
} else {
System.out.println("密码错误");
}
} else {
System.out.println("用户名不存在");
}
// 优化:使用逻辑运算符减少嵌套
if ("admin".equals(username) && "123456".equals(password) && isActive) {
System.out.println("登录成功!");
} else if (!"admin".equals(username)) {
System.out.println("用户名不存在");
} else if (!"123456".equals(password)) {
System.out.println("密码错误");
} else {
System.out.println("账户已被禁用");
}
}
}
💡 最佳实践:尽量减少嵌套层次,使用逻辑运算符或提前return来简化代码。
六、switch语句
6.1 基本语法
switch (表达式) {
case 值1:
// 表达式等于值1时执行
break;
case 值2:
// 表达式等于值2时执行
break;
case 值3:
// 表达式等于值3时执行
break;
default:
// 以上case都不匹配时执行
break;
}
6.2 支持的数据类型
| 类型 | 说明 |
|---|---|
byte |
字节型 |
short |
短整型 |
int |
整型 |
char |
字符型 |
enum |
枚举类型 |
String |
字符串(Java 7+) |
⚠️ 不支持:long、float、double、boolean
6.3 代码示例
public class SwitchDemo {
public static void main(String[] args) {
// 示例1:根据数字输出星期几
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;
case 6:
System.out.println("星期六");
break;
case 7:
System.out.println("星期日");
break;
default:
System.out.println("无效的数字");
break;
}
// 示例2:根据月份判断季节
int month = 8;
String season;
switch (month) {
case 3:
case 4:
case 5:
season = "春天";
break;
case 6:
case 7:
case 8:
season = "夏天";
break;
case 9:
case 10:
case 11:
season = "秋天";
break;
case 12:
case 1:
case 2:
season = "冬天";
break;
default:
season = "无效月份";
break;
}
System.out.println(month + "月是" + season);
// 示例3:字符串匹配(Java 7+)
String fruit = "苹果";
switch (fruit) {
case "苹果":
System.out.println("苹果的价格是5元/斤");
break;
case "香蕉":
System.out.println("香蕉的价格是3元/斤");
break;
case "橘子":
System.out.println("橘子的价格是4元/斤");
break;
default:
System.out.println("未知水果");
break;
}
}
}
6.4 switch的穿透特性
如果case后面没有break,程序会继续执行下一个case的代码,这种现象叫做"穿透"(fall-through)。
public class SwitchFallThrough {
public static void main(String[] args) {
int num = 2;
// 不小心的穿透(bug)
switch (num) {
case 1:
System.out.println("一");
// 忘记写break,会继续执行下面的case
case 2:
System.out.println("二");
// 忘记写break
case 3:
System.out.println("三");
break;
}
// 输出:二 三(穿透了)
// 故意利用穿透(多个case共享逻辑)
int month = 2;
int days;
switch (month) {
case 2:
days = 28; // 默认不考虑闰年
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
default:
days = 31;
break;
}
System.out.println(month + "月有" + days + "天");
}
}
七、switch表达式(Java 14+)
Java 14引入了switch表达式,语法更简洁,不需要break。
7.1 基本语法
// 传统switch语句
String result;
switch (day) {
case 1:
result = "星期一";
break;
case 2:
result = "星期二";
break;
default:
result = "其他";
break;
}
// switch表达式(Java 14+)
String result = switch (day) {
case 1 -> "星期一";
case 2 -> "星期二";
case 3 -> "星期三";
case 4 -> "星期四";
case 5 -> "星期五";
case 6, 7 -> "周末";
default -> "其他";
};
7.2 代码示例
public class SwitchExpressionDemo {
public static void main(String[] args) {
// 示例1:简单赋值
int day = 3;
String dayName = switch (day) {
case 1 -> "星期一";
case 2 -> "星期二";
case 3 -> "星期三";
case 4 -> "星期四";
case 5 -> "星期五";
case 6, 7 -> "周末";
default -> {
if (day < 1) {
yield "无效(太小)";
} else {
yield "无效(太大)";
}
}
};
System.out.println(day + " -> " + dayName);
// 示例2:多行代码块
int score = 85;
String level = switch (score / 10) {
case 10, 9 -> "优秀";
case 8 -> "良好";
case 7 -> "中等";
case 6 -> "及格";
default -> {
System.out.println("需要努力!");
yield "不及格";
}
};
System.out.println("等级:" + level);
// 示例3:作为方法返回值
System.out.println(getSeason(5));
}
public static String getSeason(int month) {
return switch (month) {
case 3, 4, 5 -> "春天";
case 6, 7, 8 -> "夏天";
case 9, 10, 11 -> "秋天";
case 12, 1, 2 -> "冬天";
default -> "无效月份";
};
}
}
7.3 yield关键字
在switch表达式的代码块中,使用yield返回值:
String result = switch (num) {
case 1 -> "一";
case 2 -> "二";
default -> {
// 多行代码
String msg = "数字是:" + num;
System.out.println(msg);
yield "其他"; // 使用yield返回值
}
};
八、模式匹配switch(Java 21+)
Java 21正式引入了模式匹配switch,可以对类型进行匹配。
8.1 基本语法
// 传统方式
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
} else if (obj instanceof Integer) {
Integer i = (Integer) obj;
System.out.println(i * 2);
}
// 模式匹配switch(Java 21+)
switch (obj) {
case String s -> System.out.println(s.length());
case Integer i -> System.out.println(i * 2);
case Double d -> System.out.println(d * 1.1);
case null -> System.out.println("null值");
default -> System.out.println("未知类型");
}
8.2 代码示例
public class PatternMatchSwitchDemo {
public static void main(String[] args) {
// 示例1:类型匹配
Object[] values = {"Hello", 42, 3.14, true, null};
for (Object obj : values) {
String description = switch (obj) {
case String s -> "字符串,长度:" + s.length();
case Integer i -> "整数,值:" + i;
case Double d -> "浮点数,值:" + d;
case Boolean b -> "布尔值:" + b;
case null -> "null值";
default -> "未知类型:" + obj.getClass().getSimpleName();
};
System.out.println(description);
}
// 示例2:带条件的模式匹配(guarded pattern)
Object value = "Hello World";
String result = switch (value) {
case String s && s.length() > 5 -> "长字符串:" + s;
case String s -> "短字符串:" + s;
case Integer i && i > 0 -> "正整数:" + i;
case Integer i -> "非正整数:" + i;
case null -> "null";
default -> "其他";
};
System.out.println(result);
// 示例3:密封类配合模式匹配
// sealed interface Shape permits Circle, Rectangle, Triangle {}
//
// double area = switch (shape) {
// case Circle c -> Math.PI * c.radius() * c.radius();
// case Rectangle r -> r.width() * r.height();
// case Triangle t -> 0.5 * t.base() * t.height();
// // 不需要default,编译器知道所有可能的类型
// };
}
}
8.3 null处理
Java 21的switch可以显式处理null值:
public static String describe(Object obj) {
return switch (obj) {
case null -> "这是null";
case String s -> "字符串:" + s;
case Integer i -> "整数:" + i;
default -> "其他类型";
};
}
九、条件判断实战练习
练习1:闰年判断
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
// 闰年条件:
// 1. 能被4整除但不能被100整除,或者
// 2. 能被400整除
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear) {
System.out.println(year + "年是闰年");
} else {
System.out.println(year + "年不是闰年");
}
scanner.close();
}
}
练习2:简单计算器
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个数:");
double num1 = scanner.nextDouble();
System.out.print("请输入运算符(+、-、*、/):");
char operator = scanner.next().charAt(0);
System.out.print("请输入第二个数:");
double num2 = scanner.nextDouble();
double result;
boolean valid = true;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("错误:除数不能为0!");
scanner.close();
return;
}
break;
default:
System.out.println("错误:无效的运算符!");
scanner.close();
return;
}
System.out.println(num1 + " " + operator + " " + num2 + " = " + result);
scanner.close();
}
}
练习3:成绩等级判定系统
import java.util.Scanner;
public class GradeSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生姓名:");
String name = scanner.nextLine();
System.out.print("请输入成绩(0-100):");
int score = scanner.nextInt();
// 输入验证
if (score < 0 || score > 100) {
System.out.println("错误:成绩必须在0-100之间!");
scanner.close();
return;
}
// 等级判定
String level = switch (score / 10) {
case 10, 9 -> "优秀(A)";
case 8 -> "良好(B)";
case 7 -> "中等(C)";
case 6 -> "及格(D)";
default -> "不及格(F)";
};
// 评语
String comment;
if (score >= 90) {
comment = "非常优秀,继续保持!";
} else if (score >= 80) {
comment = "表现不错,还有提升空间。";
} else if (score >= 60) {
comment = "刚刚及格,需要更加努力。";
} else {
comment = "不及格,需要好好复习。";
}
System.out.println("========== 成绩报告 ==========");
System.out.println("学生姓名:" + name);
System.out.println("考试成绩:" + score);
System.out.println("成绩等级:" + level);
System.out.println("教师评语:" + comment);
System.out.println("==============================");
scanner.close();
}
}
十、常见面试题
面试题1:if-else和switch哪个效率更高?
答案:
- 当分支较少(2-3个)时,if-else和switch效率差不多
- 当分支较多且条件是等值判断时,switch通常更高效(编译器会优化为跳转表)
- if-else适合范围判断,switch适合等值判断
面试题2:switch支持哪些数据类型?
答案:
- 基本类型:
byte、short、int、char - 引用类型:
enum(枚举)、String(Java 7+) - 不支持:
long、float、double、boolean
面试题3:switch中break的作用是什么?
答案:break用于终止switch语句的执行,防止穿透到下一个case。如果没有break,程序会继续执行后面的case代码(穿透特性)。
面试题4:case的值有什么要求?
答案:
- 必须是常量表达式(编译时就能确定的值)
- 不能是变量
- 不能重复
- 对于String,比较是区分大小写的
十一、总结与预告
本节要点回顾
| 知识点 | 核心内容 |
|---|---|
| if语句 | 单条件判断 |
| if-else | 二选一 |
| if-else if-else | 多条件判断 |
| 嵌套if | 复杂条件组合 |
| switch | 等值判断,支持穿透 |
| switch表达式 | Java 14+,更简洁的语法 |
| 模式匹配switch | Java 21+,支持类型匹配 |
🤔 互动问题
- 什么情况下应该使用switch而不是if-else?
- switch的穿透特性有哪些实际应用场景?
- 如何避免深层嵌套的if-else?
📖 下篇预告
下一篇我们将学习流程控制之循环结构——for、while、do-while循环以及break、continue控制语句,让程序能够重复执行某些操作!
📚 参考资料
- Java官方文档 - The if-then and if-then-else Statements
- Java官方文档 - The switch Statement
- JEP 361: Switch Expressions (Standard)
- JEP 441: Pattern Matching for switch
💡 学习建议:条件判断是程序逻辑的核心,建议多做练习题来熟练掌握。特别注意switch的穿透特性和Java新版本的模式匹配特性。
更多推荐




所有评论(0)