Java 核心---掌控程序流程:精通 Java 流程控制语句 🚦
作者:IvanCodes
发布时间:2025年4月29日🤓
专栏:Java教程
各位 Java 探险家们,大家好!👋 继上次我们掌握了各种运算符 之后,今天我们要学习如何真正地指挥我们的程序,让它能够 做决策 🤔、重复执行 🔄、甚至在需要时改变路线🚀!这就是 流程控制语句 (Control Flow Statements) 的魔力所在!
想象一下,没有红绿灯的十字路口会多么混乱 🚦💥,没有步骤说明的食谱多么难以操作 🍳📖。流程控制语句就是程序世界的"交通信号灯"和"执行指南",它们决定了代码的执行顺序。掌握它们,你就能编写出逻辑清晰、功能强大的应用程序!准备好成为程序的"交通指挥官"了吗?👮♀️👮♂️
一、 条件语句:让程序做出选择 🤔❓✅❌
生活充满了选择,程序也是如此。条件语句允许程序根据不同的条件执行不同的代码块。
1.1 if
语句:最简单的抉择 <☝️>
- 用途 : 当满足某个
boolean
条件时,执行一段特定的代码。 - 语法 :
if (条件表达式) { // 条件为 true 时执行的代码 }
- 比喻 : 出门前看看天,如果下雨 🌧️,就带伞 ☂️。
代码示例:
java
public class IfDemo {
public static void main(String[] args) {
int temperature = 15;
// 如果温度低于 20 度,就打印提示
if (temperature < 20) {
System.out.println("It's a bit chilly, wear a jacket! <🧥>");
}
System.out.println("Checking weather complete."); // 这句总会执行
}
}
1.2 if-else
语句:二选一的岔路口 <✌️>
- 用途 : 当条件满足时执行一段代码,否则执行另一段代码。
- 语法 :
if (条件表达式) { // 条件为 true 时执行 } else { // 条件为 false 时执行 }
- 比喻 : 考试成绩,如果及格 ✅,就庆祝 🎉;否则 ❌,就得加倍努力 💪。
代码示例:
java
public class IfElseDemo {
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. <💪>");
}
}
}
1.3 if-else if-else
语句:多重选择的菜单 <🔢>
- 用途 : 处理多个互斥的条件,按顺序检查,一旦某个条件满足,执行对应代码块后跳出整个结构。
- 语法 :
if (条件1) { ... } else if (条件2) { ... } else if (条件3) { ... } else { // 所有条件都不满足时执行 }
- 比喻 : 根据分数评级,90分以上是优秀<🅰️>,80-89是良好<🅱️>,60-79是及格<合格>,否则是不及格<不合格>。
代码示例:
java
public class IfElseIfDemo {
public static void main(String[] args) {
int grade = 78;
if (grade >= 90) {
System.out.println("Grade: Excellent <🅰️>");
} else if (grade >= 80) {
System.out.println("Grade: Good <🅱️>");
} else if (grade >= 60) {
System.out.println("Grade: Pass <合格>"); // 这个条件满足,执行并结束
} else {
System.out.println("Grade: Fail <不合格>");
}
}
}
1.4 switch
语句:精准匹配的选择器 <🎯>
-
用途 : 基于一个表达式的值 (通常是
int
,char
,String
(Java 7+),enum
),从多个case
标签中选择一个匹配的执行。比处理大量特定值的if-else if
更清晰。 -
语法 (传统):
javaswitch (表达式) { case 值1: // 代码块1 break; // <font color="red">非常重要!防止穿透</font> case 值2: // 代码块2 break; // ... 更多 case default: // <font color="orange">可选</font>,所有 case 都不匹配时执行 // 默认代码块 }
-
比喻 : 电梯按钮 🔢,按下特定楼层按钮,电梯直接去那一层。
-
关键点⚠️:
- 每个
case
后面的值必须是常量。 break
语句至关重要! 如果省略break
,程序会继续执行下一个case
的代码(称为"穿透"),这通常不是期望的行为!default
子句是可选的。
- 每个
-
Java 14+ 新特性 ✨ : 引入了更简洁的
switch
表达式 (使用->
和yield
),能返回值且默认不穿透,更安全易用。
代码示例 (传统 switch
):
java
public class SwitchDemo {
public static void main(String[] args) {
int dayOfWeek = 3; // 假设 1=周一, 2=周二, ... 7=周日
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break; // <--- 如果没有 break, 会继续执行 case 2
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break; // <--- 执行到这里,跳出 switch
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default: // 如果 dayOfWeek 不是 1-7
dayName = "Invalid day";
// default 通常不需要 break,因为它在最后
}
System.out.println("Today is: " + dayName); // Today is: Wednesday
}
}
二、 循环语句:让程序重复劳动 🔄⚙️
当需要重复执行某段代码时,循环语句就派上用场了。
2.1 for
循环:预知次数的重复 <🔢>
- 用途 : 最常用的循环结构,特别适合已知循环次数或需要控制循环变量的情况。
- 语法 :
for (初始化表达式; 循环条件; 更新表达式) { // 循环体代码 }
- 初始化表达式: 循环开始前只执行一次,通常用于声明和初始化循环控制变量。
- 循环条件: 每次循环开始前判断,若为 true 则执行循环体,false 则退出循环。
- 更新表达式: 每次循环体执行后执行,通常用于更新循环控制变量。
- 比喻 : 围着操场跑 5 圈 🏃♀️,你知道起点(初始化)、终点(条件)和每圈后的状态(更新)。
代码示例:
java
public class ForLoopDemo {
public static void main(String[] args) {
// 打印数字 0 到 4
System.out.println("Printing numbers 0 to 4:");
for (int i = 0; i < 5; i++) { // 初始化 i=0; 条件 i<5; 更新 i++
System.out.print(i + " "); // 循环体
}
System.out.println("\nLoop finished."); // 输出: 0 1 2 3 4
}
}
2.2 while
循环:条件驱动的重复 <❓>➡️🔄
- 用途 : 当循环次数不确定,但知道循环继续的条件时使用。
- 语法 :
while (循环条件) { // 循环体代码 }
- 循环开始前检查条件,条件为 true 就执行循环体,然后再次检查条件,直到条件为 false。
- 注意⚠️:循环体内部通常需要有改变循环条件的代码,否则可能导致死循环!
- 比喻 : 烧水 🔥,只要水没开(条件),就继续烧(循环体)。
代码示例:
java
public class WhileLoopDemo {
public static void main(String[] args) {
int count = 0;
System.out.println("Counting up while count < 3:");
// 当 count 小于 3 时持续循环
while (count < 3) {
System.out.println("Current count: " + count);
count++; // <--- 改变循环条件的关键步骤!
}
System.out.println("Loop finished. Final count: " + count); // 输出到 2,最后 count 变为 3 结束
}
}
2.3 do-while
循环:至少执行一次的重复 <✅>➡️<❓>➡️🔄
- 用途 : 与
while
类似,但保证循环体至少执行一次,因为条件在循环体执行后才检查。 - 语法 :
do { // 循环体代码 } while (循环条件);
注意⚠️:while
后面的分号;
不能省略! - 比喻 : 尝一口汤 🍲(至少执行一次),然后决定(检查条件)要不要再加点盐🧂并继续尝。
代码示例:
java
import java.util.Scanner;
public class DoWhileDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
// 至少提示用户输入一次,直到输入 0 才结束
do {
System.out.print("Enter a number (enter 0 to exit): ");
number = scanner.nextInt();
System.out.println("You entered: " + number);
} while (number != 0); // 条件在循环体后检查
System.out.println("Exiting program. Goodbye!");
scanner.close();
}
}
2.4 增强型 for
循环 (for-each loop):遍历集合/数组的捷径 <🚶♀️><🚶♂️>
- 用途 : 简化遍历数组或实现了
Iterable
接口的集合 (如List
,Set
) 的代码。 - 语法 :
for (元素类型 元素变量 : 集合或数组) { // 处理元素变量 }
- 优点 : 代码更简洁、易读,不易出错(如索引越界)。
- 缺点 :
- 不能获取当前元素的索引。
- 不能在循环中修改集合(通常会导致
ConcurrentModificationException
)或数组元素(对基本类型无效,对引用类型也有限制)。 - 不能用来进行需要索引的操作(如反向遍历)。
- 比喻 : 按顺序查看购物清单 🛒上的每一项,不需要关心这是第几项。
代码示例:
java
import java.util.ArrayList;
import java.util.List;
public class EnhancedForDemo {
public static void main(String[] args) {
// 遍历数组
int[] numbers = {1, 2, 3, 4, 5};
System.out.print("Array elements: ");
for (int num : numbers) { // 依次取出 numbers 中的每个元素赋给 num
System.out.print(num + " ");
}
System.out.println();
// 遍历 List 集合
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.print("List elements: ");
for (String name : names) { // 依次取出 names 中的每个元素赋给 name
System.out.print(name + " ");
}
System.out.println();
}
}
三、 跳转语句:改变常规流程的"传送门" 🚀🛑⏭️
跳转语句允许你中断正常的代码执行流程。
3.1 break
语句:紧急出口 <🛑>
- 用途 :
- 在
switch
语句中,终止一个case
的执行,防止穿透。 - 在循环语句 (
for
,while
,do-while
) 中,立即终止并跳出 当前 循环。
- 在
- 比喻 : 电影院 🎬 里的"紧急出口"标志,发生意外时直接离开。
代码示例:
java
public class BreakDemo {
public static void main(String[] args) {
System.out.println("Finding the first number divisible by 3:");
for (int i = 1; i <= 10; i++) {
System.out.println("Checking: " + i);
if (i % 3 == 0) {
System.out.println("Found it! Number is " + i);
break; // 找到后立即跳出 for 循环
}
}
System.out.println("Loop terminated.");
}
}
3.2 continue
语句:跳过这一轮 <⏭️>
- 用途 : 在循环语句中,跳过当前循环体中剩余的代码,直接开始下一次循环的判断(或更新和判断 for 循环)。
- 比喻 : 听歌单 🎶 时,遇到不喜欢的歌,直接按"下一首"。
代码示例:
java
public class ContinueDemo {
public static void main(String[] args) {
System.out.println("Printing odd numbers between 1 and 10:");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) { // 如果是偶数
continue; // 跳过本次循环的剩余部分 (println),直接进行 i++ 和下次判断
}
// 这行代码只有在 i 是奇数时才会执行
System.out.print(i + " ");
}
System.out.println("\nLoop finished."); // 输出: 1 3 5 7 9
}
}
3.3 return
语句:任务完成,撤退!<🏁><🚪>
- 用途 :
- 立即终止当前正在执行的方法。
- 如果方法有返回值类型(不是
void
),return
后面必须跟一个对应类型的值作为方法的执行结果返回给调用者。 - 如果方法是
void
类型,return;
可以用来提前结束方法执行。
- 比喻 : 完成一项任务 <✅>,向你的上司汇报结果(返回值)并离开办公室(结束方法)。
代码示例:
java
public class ReturnDemo {
// 一个有返回值的方法
public static int findMax(int a, int b) {
if (a > b) {
return a; // 返回 a 作为结果,方法结束
} else {
return b; // 返回 b 作为结果,方法结束
}
// System.out.println("This line is unreachable."); // 编译错误❌: 不可达语句
}
// 一个 void 方法,使用 return 提前结束
public static void printPositive(int num) {
if (num <= 0) {
System.out.println("Number is not positive. Exiting method.");
return; // 提前结束 void 方法
}
System.out.println("The positive number is: " + num);
}
public static void main(String[] args) {
int maxVal = findMax(10, 25);
System.out.println("Maximum value is: " + maxVal); // Maximum value is: 25
printPositive(5); // The positive number is: 5
printPositive(-3); // Number is not positive. Exiting method.
}
}
四、总结 ✨🧭
流程控制语句是编程的"神经系统",它们让我们的代码能够根据条件和需求,灵活地决定执行路径:
- 条件语句 (
if
,else
,switch
) 🤔:让程序在不同的路径中做选择。 - 循环语句 (
for
,while
,do-while
, enhancedfor
) 🔄:让程序重复执行任务。 - 跳转语句 (
break
,continue
,return
) 🚀:在需要时改变正常的执行流程。
熟练运用这些语句,你就能构建出逻辑严谨、行为丰富的 Java 程序!继续练习,成为真正的"代码指挥官"吧! 👨✈️👩✈️
五、练练手,检验成果!✏️🧠
实践是检验真理的唯一标准!来试试这些练习题吧:
⭐ 条件与选择 ⭐
- 使用
if-else if-else
结构,根据用户输入的月份 (1-12),打印对应的季节(例如,3-5 月为春季,6-8 月为夏季,9-11 月为秋季,12, 1, 2 月为冬季)。 - 使用
switch
语句(传统或新式均可),根据一个字符变量grade
的值 ('A', 'B', 'C', 'D', 'F'),打印出相应的评价 ("Excellent", "Good", "Average", "Pass", "Fail")。处理无效等级的情况。
⭐ 循环与迭代 ⭐
- 使用
for
循环计算 1 到 100 之间所有偶数的和。 - 使用
while
循环,模拟一个简单的猜数字游戏:程序随机生成一个 1 到 100 之间的整数,让用户不断输入猜测的数字,直到猜对为止。每次猜测后提示用户猜高了还是猜低了。 - 创建一个包含几个水果名称的
String
数组,使用增强型for
循环打印出数组中的所有水果名称。
⭐ 跳转与控制 ⭐
- 编写一个循环,查找数组
int[] numbers = {2, 5, 8, 12, 7, 10};
中第一个大于 10 的数字,找到后立即打印该数字并终止循环。 - 编写一个循环,计算数组
int[] scores = {85, 92, -1, 78, 95};
中所有有效分数(大于等于 0)的总和,忽略无效分数(负数)。
六、参考答案 ✅💡
⭐ 条件与选择答案 ⭐
-
月份判断季节:
javaimport java.util.Scanner; public class SeasonChecker { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the month (1-12): "); int month = input.nextInt(); String season; if (month >= 3 && month <= 5) { season = "Spring <🌸>"; } else if (month >= 6 && month <= 8) { season = "Summer <☀️>"; } else if (month >= 9 && month <= 11) { season = "Autumn <🍁>"; } else if (month == 12 || month == 1 || month == 2) { season = "Winter <❄️>"; } else { season = "Invalid month"; } System.out.println("The season is: " + season); input.close(); } }
-
成绩评价 (使用传统
switch
):javapublic class GradeEvaluator { public static void main(String[] args) { char grade = 'B'; // 示例等级 String evaluation; switch (grade) { case 'A': evaluation = "Excellent <🏆>"; break; case 'B': evaluation = "Good <👍>"; break; case 'C': evaluation = "Average <👌>"; break; case 'D': evaluation = "Pass <✔️>"; break; case 'F': evaluation = "Fail <👎>"; break; default: evaluation = "Invalid grade <❓>"; } System.out.println("Evaluation for grade " + grade + ": " + evaluation); } }
(使用 Java 14+
switch
表达式会更简洁)
⭐ 循环与迭代答案 ⭐
-
计算偶数和:
javapublic class SumEvenNumbers { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 100; i++) { if (i % 2 == 0) { // 判断是否为偶数 sum += i; } } System.out.println("Sum of even numbers from 1 to 100: " + sum); // 结果是 2550 } }
-
猜数字游戏:
javaimport java.util.Random; import java.util.Scanner; public class GuessNumberGame { public static void main(String[] args) { Random random = new Random(); int numberToGuess = random.nextInt(100) + 1; // 生成 1 到 100 的随机数 Scanner scanner = new Scanner(System.in); int userGuess = 0; int attempts = 0; System.out.println("Guess the number between 1 and 100!"); while (userGuess != numberToGuess) { System.out.print("Enter your guess: "); userGuess = scanner.nextInt(); attempts++; if (userGuess < numberToGuess) { System.out.println("Too low! Try again."); } else if (userGuess > numberToGuess) { System.out.println("Too high! Try again."); } else { System.out.println("Correct! You guessed the number " + numberToGuess + " in " + attempts + " attempts! <🎉>"); } } scanner.close(); } }
-
遍历水果数组:
javapublic class PrintFruits { public static void main(String[] args) { String[] fruits = {"Apple <🍎>", "Banana <🍌>", "Orange <🍊>", "Grape <🍇>"}; System.out.println("Fruits in the array:"); for (String fruit : fruits) { System.out.println("- " + fruit); } } }
⭐ 跳转与控制答案 ⭐
-
查找第一个大于 10 的数:
javapublic class FindFirstLargeNumber { public static void main(String[] args) { int[] numbers = {2, 5, 8, 12, 7, 10}; System.out.println("Searching for the first number > 10..."); for (int number : numbers) { if (number > 10) { System.out.println("Found: " + number); break; // 找到后立即终止循环 } System.out.println("Checked: " + number + " (not > 10)"); } } }
-
计算有效分数总和:
javapublic class SumValidScores { public static void main(String[] args) { int[] scores = {85, 92, -1, 78, 95}; int sum = 0; System.out.println("Calculating sum of valid scores (>= 0)..."); for (int score : scores) { if (score < 0) { System.out.println("Skipping invalid score: " + score); continue; // 跳过当前无效分数,继续下一次循环 } sum += score; // 累加有效分数 } System.out.println("Total sum of valid scores: " + sum); // 85 + 92 + 78 + 95 = 350 } }
希望这篇关于流程控制语句的笔记对你有所帮助!多写代码,多练习,才能真正掌握这些编程的"指挥棒"哦!如果觉得有用,请点赞👍、收藏⭐、关注支持一下!谢谢!💖