📋 目录结构
流程控制语句
├── 顺序结构 (默认)
├── 分支结构
│ ├── if 语句
│ ├── if-else 语句
│ ├── if-else if-else 语句
│ ├── switch 语句
│ └── 三目运算符
├── 循环结构
│ ├── for 循环
│ ├── while 循环
│ ├── do-while 循环
│ └── 增强for循环
└── 跳转语句
├── break
├── continue
└── return
🛣️ 顺序结构(默认)
public class SequentialStructure {
public static void main(String[] args) {
// 代码按照从上到下的顺序执行
System.out.println("第一步");
int x = 10;
int y = 20;
int sum = x + y;
System.out.println("计算结果:" + sum);
System.out.println("最后一步");
// 输出:
// 第一步
// 计算结果:30
// 最后一步
}
}
🌳 分支结构
1. if 语句
public class IfStatement {
public static void main(String[] args) {
// 基本形式
int score = 85;
if (score >= 60) {
System.out.println("及格");
}
// 单行写法(不建议)
if (score >= 60) System.out.println("及格");
// 嵌套if
if (score >= 90) {
if (score >= 95) {
System.out.println("优秀");
} else {
System.out.println("良好");
}
}
}
}
2. if-else 语句
public class IfElseStatement {
public static void main(String[] args) {
int age = 18;
// 标准形式
if (age >= 18) {
System.out.println("成年人");
} else {
System.out.println("未成年人");
}
// 示例:判断奇偶数
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " 是偶数");
} else {
System.out.println(number + " 是奇数");
}
}
}
3. if-else if-else 语句
public class IfElseIfStatement {
public static void main(String[] args) {
int score = 85;
char grade;
// 多条件判断
if (score >= 90) {
grade = 'A';
System.out.println("优秀");
} else if (score >= 80) {
grade = 'B';
System.out.println("良好");
} else if (score >= 70) {
grade = 'C';
System.out.println("中等");
} else if (score >= 60) {
grade = 'D';
System.out.println("及格");
} else {
grade = 'F';
System.out.println("不及格");
}
System.out.println("成绩等级:" + grade);
// 注意:条件顺序很重要!
// ❌ 错误示例
/*
if (score >= 60) {
System.out.println("及格");
} else if (score >= 70) { // 这个条件永远不会执行!
System.out.println("中等");
}
*/
}
}
4. switch 语句
public class SwitchStatement {
public static void main(String[] args) {
// 传统switch(Java 7之前)
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;
}
// 穿透效果(多个case执行相同代码)
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
case 'C':
System.out.println("通过");
break;
case 'D':
case 'F':
System.out.println("未通过");
break;
default:
System.out.println("无效等级");
}
// Java 7+:支持String
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("苹果");
break;
case "banana":
System.out.println("香蕉");
break;
default:
System.out.println("未知水果");
}
// Java 12+:新的switch表达式(更简洁)
int month = 3;
String season = switch (month) {
case 12, 1, 2 -> "冬季";
case 3, 4, 5 -> "春季";
case 6, 7, 8 -> "夏季";
case 9, 10, 11 -> "秋季";
default -> "无效月份";
};
System.out.println("季节:" + season);
}
}
5. 三目运算符(条件运算符)
public class TernaryOperator {
public static void main(String[] args) {
// 语法:条件 ? 表达式1 : 表达式2
int a = 10, b = 20;
// 找出最大值
int max = (a > b) ? a : b;
System.out.println("最大值:" + max);
// 判断奇偶数
int num = 15;
String result = (num % 2 == 0) ? "偶数" : "奇数";
System.out.println(num + "是" + result);
// 嵌套三目运算符(可读性差,慎用)
int score = 85;
String grade = (score >= 90) ? "优秀" :
(score >= 80) ? "良好" :
(score >= 60) ? "及格" : "不及格";
System.out.println("成绩等级:" + grade);
// vs if-else 写法
if (score >= 90) {
grade = "优秀";
} else if (score >= 80) {
grade = "良好";
} else if (score >= 60) {
grade = "及格";
} else {
grade = "不及格";
}
}
}
🔄 循环结构
1. for 循环
public class ForLoop {
public static void main(String[] args) {
// 基本for循环
System.out.println("=== 基本for循环 ===");
for (int i = 0; i < 5; i++) {
System.out.println("i = " + i);
}
// 输出乘法表
System.out.println("\n=== 九九乘法表 ===");
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();
}
// 多个初始化/更新表达式
System.out.println("\n=== 多个表达式 ===");
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i = " + i + ", j = " + j);
}
// 无限循环(慎用)
// for (;;) {
// System.out.println("无限循环");
// }
}
}
2. while 循环
public class WhileLoop {
public static void main(String[] args) {
// 基本while循环
System.out.println("=== 基本while循环 ===");
int count = 0;
while (count < 5) {
System.out.println("count = " + count);
count++;
}
// 计算1-100的和
System.out.println("\n=== 计算1-100的和 ===");
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("1-100的和:" + sum);
// 用户输入验证(模拟)
System.out.println("\n=== 输入验证(模拟)===");
int input = -1;
java.util.Scanner scanner = new java.util.Scanner(System.in);
while (input < 0 || input > 100) {
System.out.print("请输入0-100之间的数:");
input = scanner.nextInt();
if (input < 0 || input > 100) {
System.out.println("输入无效,请重新输入!");
}
}
System.out.println("你输入了:" + input);
// 无限循环
// while (true) {
// // 需要break退出
// }
}
}
3. do-while 循环
public class DoWhileLoop {
public static void main(String[] args) {
// do-while:至少执行一次
System.out.println("=== do-while循环 ===");
int count = 0;
do {
System.out.println("count = " + count);
count++;
} while (count < 5);
// 与while的区别:条件不成立也执行一次
System.out.println("\n=== while vs do-while ===");
int x = 10;
while (x < 5) { // 条件不成立
System.out.println("while循环"); // 不会执行
}
int y = 10;
do {
System.out.println("do-while循环"); // 执行一次
} while (y < 5);
// 菜单选择示例
System.out.println("\n=== 菜单选择 ===");
java.util.Scanner scanner = new java.util.Scanner(System.in);
int choice;
do {
System.out.println("\n=== 菜单 ===");
System.out.println("1. 查看信息");
System.out.println("2. 修改信息");
System.out.println("3. 退出");
System.out.print("请选择:");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("查看信息...");
break;
case 2:
System.out.println("修改信息...");
break;
case 3:
System.out.println("退出程序");
break;
default:
System.out.println("无效选择");
}
} while (choice != 3);
}
}
4. 增强for循环(for-each)
public class EnhancedForLoop {
public static void main(String[] args) {
// 遍历数组
System.out.println("=== 遍历数组 ===");
int[] numbers = {1, 2, 3, 4, 5};
// 传统for循环
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
// 增强for循环(更简洁)
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
// 遍历集合
System.out.println("\n=== 遍历集合 ===");
java.util.ArrayList<String> list = new java.util.ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
for (String language : list) {
System.out.println(language);
}
// 遍历二维数组
System.out.println("\n=== 遍历二维数组 ===");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
// 限制:不能修改元素值,不能获取索引
for (int num : numbers) {
num = num * 2; // 修改的是副本,不影响原数组
// 如果需要索引,还是要用传统for循环
}
}
}
🚀 跳转语句
1. break 语句
public class BreakStatement {
public static void main(String[] args) {
// 1. 在switch中终止case穿透
System.out.println("=== 在switch中使用 ===");
// 2. 退出循环
System.out.println("=== 退出循环 ===");
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // i=5时退出循环
}
System.out.println("i = " + i);
}
// 3. 嵌套循环中break只退出当前循环
System.out.println("\n=== 嵌套循环 ===");
for (int i = 0; i < 3; i++) {
System.out.println("外层 i = " + i);
for (int j = 0; j < 3; j++) {
if (j == 1) {
break; // 只退出内层循环
}
System.out.println(" 内层 j = " + j);
}
}
// 4. 带标签的break(退出指定循环)
System.out.println("\n=== 带标签的break ===");
outer: // 标签
for (int i = 0; i < 3; i++) {
System.out.println("外层 i = " + i);
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
break outer; // 退出外层循环
}
System.out.println(" 内层 j = " + j);
}
}
System.out.println("循环结束");
// 5. 在while/do-while中使用
System.out.println("\n=== 在while中使用 ===");
int num = 0;
while (true) { // 无限循环
System.out.println("num = " + num);
num++;
if (num >= 5) {
break; // 退出循环
}
}
}
}
2. continue 语句
public class ContinueStatement {
public static void main(String[] args) {
// 跳过当前循环的剩余部分,继续下一次循环
System.out.println("=== 跳过偶数 ===");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 跳过偶数
}
System.out.print(i + " ");
}
System.out.println();
// 计算1-100奇数的和
System.out.println("\n=== 计算奇数和 ===");
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
continue; // 偶数跳过
}
sum += i;
}
System.out.println("1-100奇数和:" + sum);
// 在while循环中使用
System.out.println("\n=== while中使用continue ===");
int count = 0;
while (count < 10) {
count++;
if (count % 3 == 0) {
continue; // 3的倍数跳过
}
System.out.print(count + " ");
}
System.out.println();
// 带标签的continue
System.out.println("\n=== 带标签的continue ===");
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
continue outer; // 跳到外层循环的下一次迭代
}
System.out.println("i=" + i + ", j=" + j);
}
}
}
}
3. return 语句
public class ReturnStatement {
// 从方法返回值
public static int add(int a, int b) {
return a + b; // 返回计算结果
}
// 提前退出方法
public static void checkAge(int age) {
if (age < 0) {
System.out.println("年龄无效");
return; // 提前退出方法
}
if (age >= 18) {
System.out.println("成年人");
} else {
System.out.println("未成年人");
}
}
// 返回对象
public static String getGrade(int score) {
if (score >= 90) return "优秀";
if (score >= 80) return "良好";
if (score >= 60) return "及格";
return "不及格"; // 最后的return
}
public static void main(String[] args) {
// 调用有返回值的方法
int result = add(10, 20);
System.out.println("10 + 20 = " + result);
// 调用无返回值的方法
checkAge(25);
checkAge(-5); // 会提前返回
// 获取等级
String grade = getGrade(85);
System.out.println("成绩等级:" + grade);
// main方法中的return
System.out.println("\n=== main方法中的return ===");
for (int i = 0; i < 10; i++) {
if (i == 5) {
System.out.println("遇到5,退出main方法");
return; // 退出main方法,程序结束
}
System.out.println("i = " + i);
}
System.out.println("这行不会执行");
}
}
💡 最佳实践与常见错误
1. if-else 优化
public class IfElseBestPractice {
public static void main(String[] args) {
// ❌ 不好的写法
boolean isRainy = true;
boolean haveUmbrella = true;
if (isRainy == true) { // 冗余的==true
if (haveUmbrella == true) {
System.out.println("带伞出门");
} else {
System.out.println("等雨停");
}
} else {
System.out.println("直接出门");
}
// ✅ 好的写法
if (isRainy) { // 直接使用布尔变量
if (haveUmbrella) {
System.out.println("带伞出门");
} else {
System.out.println("等雨停");
}
} else {
System.out.println("直接出门");
}
// ✅ 更简洁的写法(使用提前返回)
if (!isRainy) {
System.out.println("直接出门");
return;
}
if (haveUmbrella) {
System.out.println("带伞出门");
} else {
System.out.println("等雨停");
}
}
}
2. 循环优化
public class LoopOptimization {
public static void main(String[] args) {
// ❌ 不好的写法
int[] arr = new int[1000];
for (int i = 0; i < arr.length; i++) { // 每次循环都计算length
// 复杂操作
}
// ✅ 好的写法
int length = arr.length; // 缓存长度
for (int i = 0; i < length; i++) {
// 复杂操作
}
// ✅ 更好的写法(倒序循环)
for (int i = arr.length - 1; i >= 0; i--) {
// 某些情况下效率更高
}
}
}
3. switch 常见错误
public class SwitchCommonMistakes {
public static void main(String[] args) {
// ❌ 忘记break(非故意的穿透)
int option = 1;
switch (option) {
case 1:
System.out.println("选项1");
// 忘记break!
case 2:
System.out.println("选项2");
break;
case 3:
System.out.println("选项3");
break;
}
// 输出:选项1 选项2(不是预期的结果)
// ❌ default位置不当
switch (option) {
default: // 应该放在最后
System.out.println("默认");
break;
case 1:
System.out.println("选项1");
break;
}
// ✅ 好的写法
switch (option) {
case 1:
System.out.println("选项1");
break;
case 2:
System.out.println("选项2");
break;
case 3:
System.out.println("选项3");
break;
default: // 放在最后
System.out.println("无效选项");
break;
}
}
}
🎯 综合练习
练习1:判断闰年
public class LeapYearChecker {
public static void main(String[] args) {
int year = 2024;
// 闰年规则:
// 1. 能被4整除但不能被100整除
// 2. 能被400整除
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println(year + "年是闰年");
} else {
System.out.println(year + "年不是闰年");
}
}
}
练习2:打印金字塔
public class PyramidPrinter {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
// 打印空格
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// 打印星号
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
}
}
练习3:素数判断
public class PrimeNumberChecker {
public static void main(String[] args) {
int num = 17;
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
// 优化:只需要检查到√num
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + "是素数");
} else {
System.out.println(num + "不是素数");
}
}
}
📊 流程控制总结表
| 语句类型 | 关键字 | 用途 | 特点 |
|---|---|---|---|
| 条件判断 | if | 单条件判断 | 基础条件语句 |
| if-else | 二选一 | 两个分支 | |
| if-else if-else | 多条件判断 | 多个分支 | |
| switch | 等值判断 | 可读性好,支持穿透 | |
| ?: | 简单条件赋值 | 简洁,但可读性差 | |
| 循环 | for | 已知循环次数 | 最常用,功能全面 |
| while | 条件循环 | 先判断后执行 | |
| do-while | 条件循环 | 至少执行一次 | |
| for-each | 遍历集合/数组 | 简洁,但不能修改元素 | |
| 跳转 | break | 退出循环/switch | 可带标签 |
| continue | 跳过本次循环 | 继续下一次 | |
| return | 退出方法 | 可返回值 |
🎓 学习建议
- 理解执行流程:画流程图帮助理解
- 避免深层嵌套:嵌套超过3层考虑重构
- 合理使用提前返回:减少else嵌套
- 循环边界检查:注意off-by-one错误
- switch注意break:避免意外穿透
- 性能考虑:大循环内避免重复计算
记住:清晰的流程控制是写出可读性高、易维护代码的关键!