【java第17集】java流程控制语句详解
文章目录
- 1. 顺序结构
- 2. 选择结构
- 2.1 `if` 语句
- 2.2 `if-else` 语句
- 2.3 `if-else if-else` 语句
- 2.4 `switch` 语句
- 3. 循环结构
- 3.1 `for` 循环
- 3.2 `while` 循环
- 3.3 `do-while` 循环
- 4. 跳转语句
- 4.1 `break`
- 4.2 `continue`
- 4.3 `return`
- 5. 增强型 `for` 循环(`foreach`)
- 6. 常见问题与解决方案
- 7. 总结对比
1. 顺序结构
顺序结构是 Java 最基础的流程控制方式,代码从上到下依次执行,无需任何判断或循环。
- 示例代码
public class SequenceExample {public static void main(String[] args) {System.out.println("第一步");System.out.println("第二步");System.out.println("第三步");}
}
- 输出结果:
第一步
第二步
第三步
2. 选择结构
选择结构根据条件的真假决定执行哪条分支路径,包括 if
、if-else
、if-else if-else
和 switch
。
2.1 if
语句
-
用途:当条件为
true
时执行某段代码。 -
语法:
if (条件表达式) {// 条件为 true 时执行的代码 }
-
示例代码
public class IfExample {public static void main(String[] args) {int temperature = 15;if (temperature < 20) {System.out.println("It's a bit chilly, wear a jacket!");}}
}
2.2 if-else
语句
-
用途:条件为
true
时执行一段代码,否则执行另一段代码。 -
语法:
if (条件表达式) {// 条件为 true 时执行的代码 } else {// 条件为 false 时执行的代码 }
-
示例代码
public class IfElseExample {public static void main(String[] args) {int score = 55;if (score >= 60) {System.out.println("Congratulations! You passed!");} else {System.out.println("Keep trying! You failed this time.");}}
}
2.3 if-else if-else
语句
-
用途:多条件判断,按顺序匹配第一个为
true
的条件分支。 -
语法:
if (条件1) {// 条件1 为 true 时执行 } else if (条件2) {// 条件2 为 true 时执行 } else {// 所有条件都不满足时执行 }
-
示例代码
public class IfElseIfElseExample {public static void main(String[] args) {int score = 85;if (score >= 90) {System.out.println("成绩为优秀");} else if (score >= 75) {System.out.println("成绩为良好");} else if (score >= 60) {System.out.println("成绩为及格");} else {System.out.println("成绩为不及格");}}
}
2.4 switch
语句
-
用途:根据变量的值匹配对应的
case
分支,适用于固定选项的多路分支。 -
语法:
switch (变量) {case 值1:// 匹配值1 时执行break;case 值2:// 匹配值2 时执行break;default:// 默认分支(可选) }
-
注意事项
- case 穿透:若
case
分支未加break
,会继续执行后续的case
或default
。 - Java 12+ 支持 switch 表达式:可直接返回值(如
int day = switch (month) { ... };
)。
- case 穿透:若
-
示例代码
public class SwitchExample {public static void main(String[] args) {int weekDay = 3;switch (weekDay) {case 1:System.out.println("周一例会");break;case 2:System.out.println("周二培训");break;case 3:System.out.println("周三团建");// 没有 break,会继续执行 case 4case 4:System.out.println("周四写代码");break;default:System.out.println("休息日");}}
}
3. 循环结构
循环结构用于重复执行代码块,包括 for
、while
和 do-while
。
3.1 for
循环
-
用途:已知循环次数时使用。
-
语法:
for (初始化; 条件; 迭代) {// 循环体 }
-
示例代码
public class ForExample {public static void main(String[] args) {// 计算 1 到 100 的和int sum = 0;for (int i = 1; i <= 100; i++) {sum += i;}System.out.println("sum = " + sum);}
}
3.2 while
循环
-
用途:条件满足时循环执行,适用于未知循环次数的情况。
-
语法:
while (条件) {// 循环体 }
-
示例代码
public class WhileExample {public static void main(String[] args) {int count = 0;while (count < 5) {System.out.println("第 " + (count + 1) + " 次尝试");count++;}}
}
3.3 do-while
循环
-
用途:至少执行一次循环体,再判断条件。
-
语法:
do {// 循环体 } while (条件);
-
示例代码
public class DoWhileExample {public static void main(String[] args) {int input;do {System.out.print("请输入 1-100 的数字:");Scanner scanner = new Scanner(System.in);input = scanner.nextInt();} while (input < 1 || input > 100);System.out.println("输入合法!");}
}
4. 跳转语句
跳转语句用于控制循环或分支的执行流程,包括 break
、continue
和 return
。
4.1 break
- 用途:立即退出当前循环或
switch
语句。 - 示例代码
public class BreakExample {public static void main(String[] args) {for (int i = 1; i <= 10; i++) {if (i == 5) {break; // 当 i=5 时退出循环}System.out.print(i + " ");}}
}
// 输出:1 2 3 4
4.2 continue
- 用途:跳过当前循环体的剩余部分,直接进入下一次循环。
- 示例代码
public class ContinueExample {public static void main(String[] args) {for (int i = 1; i <= 10; i++) {if (i % 2 == 0) {continue; // 跳过偶数}System.out.print(i + " ");}}
}
// 输出:1 3 5 7 9
4.3 return
- 用途:退出当前方法并返回值(若方法有返回值类型)。
- 示例代码
public class ReturnExample {public static void main(String[] args) {int result = calculateSum(10);System.out.println("结果:" + result);}public static int calculateSum(int n) {int sum = 0;for (int i = 1; i <= n; i++) {sum += i;}return sum;}
}
5. 增强型 for
循环(foreach
)
-
用途:遍历数组或集合,简化代码。
-
语法:
for (元素类型 元素变量 : 集合/数组) {// 处理元素 }
-
示例代码
public class ForEachExample {public static void main(String[] args) {int[] numbers = {10, 20, 30, 40, 50};for (int num : numbers) {System.out.print(num + " ");}}
}
// 输出:10 20 30 40 50
6. 常见问题与解决方案
Q1: switch
语句中忘记写 break
会怎样?
- 现象:发生 case 穿透,即匹配到某个
case
后继续执行后续case
或default
。 - 解决方案:在每个
case
结尾添加break
(或使用switch
表达式返回值)。
Q2: while
循环可能导致死循环吗?
- 原因:条件始终为
true
或迭代逻辑错误。 - 示例:
int i = 1; while (i <= 10) {System.out.println(i); // 死循环,i 不更新 }
- 解决方案:确保循环条件能变为
false
,并正确更新变量。
Q3: 如何避免 if-else
多层嵌套?
- 方法:
- 使用
switch
替代多层if-else
。 - 提前返回(
return
)减少嵌套层级。 - 使用策略模式或工具类拆分逻辑。
- 使用
7. 总结对比
控制结构 | 特点 | 适用场景 |
---|---|---|
顺序结构 | 代码从上到下依次执行 | 简单逻辑处理 |
选择结构 | 根据条件执行不同分支 | 条件判断(如登录验证、成绩分级) |
循环结构 | 重复执行代码块 | 遍历数据、累加计算、等待用户输入等 |
跳转语句 | 控制流程跳转(break 、continue 、return ) | 提前退出循环或方法 |
增强型 for | 简化集合或数组遍历 | 遍历集合、数组等可迭代对象 |