Java流程控制详解
1. 流程控制概述
程序流程控制语句用于控制程序的执行顺序,是编程中的核心概念。Java提供了三种主要的流程控制结构:
- 顺序结构:程序从上到下依次执行
- 判断结构:根据条件决定执行路径
- 循环结构:重复执行特定代码块
2. 判断结构:if语句
2.1 if语句的三种格式
Java中的if语句有三种基本格式,用于实现不同的条件判断逻辑。
格式一:单分支if语句
语法格式:
if (条件表达式) {
执行语句
}
执行流程:
- 判断条件表达式的值
- 如果为true,执行语句块
- 如果为false,跳过语句块
示例代码:
public class IfDemo1 {
public static void main(String[] args) {
int age = 18;
if (age >= 18) {
System.out.println("已成年,可以投票");
}
int score = 85;
if (score >= 60) {
System.out.println("考试及格");
}
System.out.println("程序继续执行");
}
}
格式二:双分支if-else语句
语法格式:
if (条件表达式) {
执行语句1
} else {
执行语句2
}
执行特点:
- 条件表达式为true时,执行语句1
- 条件表达式为false时,执行语句2
- 两个分支必定执行其中一个
示例代码:
public class IfDemo2 {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " 是偶数");
} else {
System.out.println(number + " 是奇数");
}
// 判断最大值
int a = 10, b = 20;
if (a > b) {
System.out.println("最大值是: " + a);
} else {
System.out.println("最大值是: " + b);
}
}
}
格式三:多分支if-else if-else语句
语法格式:
if (条件表达式1) {
执行语句1
} else if (条件表达式2) {
执行语句2
} else if (条件表达式3) {
执行语句3
} else {
执行语句4
}
执行特点:
- 从上到下依次判断条件
- 只要有一个条件满足,执行对应语句并结束整个if结构
- 如果所有条件都不满足,执行else语句块
示例代码:
public class IfDemo3 {
public static void main(String[] args) {
// 成绩等级判断
int score = 92;
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("等级:不及格");
}
// 季节判断
int month = 8;
if (month >= 3 && month <= 5) {
System.out.println("春季");
} else if (month >= 6 && month <= 8) {
System.out.println("夏季");
} else if (month >= 9 && month <= 11) {
System.out.println("秋季");
} else {
System.out.println("冬季");
}
}
}
2.2 if语句与多个if语句的区别
多个独立if语句:
if (条件表达式1) {
运行语句1
}
if (条件表达式2) { // 不管条件表达式1是否true,继续判断
运行语句2
}
// ... 可能还有更多if语句
if-else if结构:
if (条件表达式1) {
执行语句1
} else if (条件表达式2) { // 只有条件表达式1为false时才判断
执行语句2
}
对比示例:
public class IfCompareDemo {
public static void main(String[] args) {
int score = 95;
System.out.println("=== 多个独立if语句 ===");
if (score >= 90) {
System.out.println("优秀");
}
if (score >= 80) { // 仍然会判断和执行
System.out.println("良好");
}
if (score >= 60) { // 仍然会判断和执行
System.out.println("及格");
}
System.out.println("=== if-else if结构 ===");
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) { // 不会执行
System.out.println("良好");
} else if (score >= 60) { // 不会执行
System.out.println("及格");
}
}
}
输出结果:
=== 多个独立if语句 ===
优秀
良好
及格
=== if-else if结构 ===
优秀
2.3 if语句最佳实践
public class IfBestPractice {
public static void main(String[] args) {
// 1. 避免过深的嵌套
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = true;
// 不推荐:嵌套过深
if (age >= 18) {
if (hasLicense) {
if (hasInsurance) {
System.out.println("可以开车");
} else {
System.out.println("需要保险");
}
} else {
System.out.println("需要驾照");
}
} else {
System.out.println("年龄不够");
}
// 推荐:提前返回或使用逻辑运算符
if (age < 18) {
System.out.println("年龄不够");
return;
}
if (!hasLicense) {
System.out.println("需要驾照");
return;
}
if (!hasInsurance) {
System.out.println("需要保险");
return;
}
System.out.println("可以开车");
// 2. 使用逻辑运算符简化条件
if (age >= 18 && hasLicense && hasInsurance) {
System.out.println("满足开车条件");
} else {
System.out.println("不满足开车条件");
}
// 3. 使用括号明确优先级
boolean isWeekend = true;
boolean isHoliday = false;
int temperature = 25;
if ((isWeekend || isHoliday) && temperature > 20) {
System.out.println("适合出游");
}
}
}
3. 选择结构:switch语句
3.1 switch语句格式
语法格式:
switch (条件表达式) {
case 取值1:
执行语句1;
break;
case 取值2:
执行语句2;
break;
case 取值3:
执行语句3;
break;
default:
默认执行语句;
break; // 最后一个break可以省略
}
重要特点:
- 条件表达式只接受
byte、short、int、char、String(JDK 7+)、枚举类型 - case穿透:找到匹配的case后,会执行后续所有语句直到遇到break或程序结束
- default:可选,当所有case都不匹配时执行
3.2 switch语句基本使用
public class SwitchDemo {
public static void main(String[] args) {
// 基本用法:星期判断
int dayOfWeek = 3;
switch (dayOfWeek) {
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;
}
// 字符类型switch
char grade = 'B';
switch (grade) {
case 'A':
case 'a':
System.out.println("优秀");
break;
case 'B':
case 'b':
System.out.println("良好");
break;
case 'C':
case 'c':
System.out.println("中等");
break;
case 'D':
case 'd':
System.out.println("及格");
break;
case 'F':
case 'f':
System.out.println("不及格");
break;
default:
System.out.println("无效等级");
}
// 字符串类型switch(JDK 7+)
String operation = "add";
switch (operation) {
case "add":
System.out.println("执行加法操作");
break;
case "subtract":
System.out.println("执行减法操作");
break;
case "multiply":
System.out.println("执行乘法操作");
break;
case "divide":
System.out.println("执行除法操作");
break;
default:
System.out.println("未知操作");
}
}
}
3.3 switch穿透特性
switch语句的一个重要特性是case穿透:一旦找到匹配的case,就会执行后续所有语句,直到遇到break或程序结束。
public class SwitchFallThrough {
public static void main(String[] args) {
// 演示穿透特性
int number = 2;
System.out.println("=== 没有break的情况 ===");
switch (number) {
case 1:
System.out.println("执行case 1");
case 2:
System.out.println("执行case 2");
case 3:
System.out.println("执行case 3");
default:
System.out.println("执行default");
}
System.out.println("=== 有break的情况 ===");
switch (number) {
case 1:
System.out.println("执行case 1");
break;
case 2:
System.out.println("执行case 2");
break;
case 3:
System.out.println("执行case 3");
break;
default:
System.out.println("执行default");
}
// 利用穿透特性实现多值匹配
int month = 8;
System.out.println("=== 利用穿透特性 ===");
switch (month) {
case 12:
case 1:
case 2:
System.out.println("冬季");
break;
case 3:
case 4:
case 5:
System.out.println("春季");
break;
case 6:
case 7:
case 8:
System.out.println("夏季");
break;
case 9:
case 10:
case 11:
System.out.println("秋季");
break;
default:
System.out.println("无效月份");
}
}
}
输出结果:
=== 没有break的情况 ===
执行case 2
执行case 3
执行default
=== 有break的情况 ===
执行case 2
=== 利用穿透特性 ===
夏季
3.4 switch与if-else的选择
使用switch的场景:
- 判断条件是等值比较
- 判断的值是固定的几个选项
- case分支较多(通常3个以上)
使用if-else的场景:
- 需要范围判断
- 需要复杂的逻辑判断
- 判断条件不是等值比较
public class SwitchVsIf {
public static void main(String[] args) {
// 适合用switch:固定选项判断
int menuChoice = 2;
switch (menuChoice) {
case 1: System.out.println("新建文件"); break;
case 2: System.out.println("打开文件"); break;
case 3: System.out.println("保存文件"); break;
case 4: System.out.println("退出程序"); break;
default: System.out.println("无效选择");
}
// 适合用if-else:范围判断
int score = 85;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}
// 适合用if-else:复杂逻辑判断
boolean isStudent = true;
int age = 20;
double income = 15000;
if (isStudent && age < 25) {
System.out.println("学生票价");
} else if (age >= 60 || income < 20000) {
System.out.println("优惠票价");
} else {
System.out.println("标准票价");
}
}
}
4. 循环结构
循环结构用于重复执行代码块,Java提供了三种循环语句:while、do-while和for。
4.1 while循环
语法格式:
while (条件表达式) {
执行语句
}
执行流程:
- 判断条件表达式
- 如果为true,执行循环体
- 执行完毕后返回步骤1
- 如果为false,结束循环
基本示例:
public class WhileDemo {
public static void main(String[] args) {
// 基本while循环
int i = 1;
while (i <= 5) {
System.out.println("第" + i + "次循环");
i++; // 必须有改变条件的语句,否则死循环
}
// 计算1到100的和
int sum = 0;
int num = 1;
while (num <= 100) {
sum += num;
num++;
}
System.out.println("1到100的和是: " + sum);
// 找到第一个大于1000的2的幂次
int power = 1;
int exponent = 0;
while (power <= 1000) {
power *= 2;
exponent++;
}
System.out.println("第一个大于1000的2的幂次是: 2^" + exponent + " = " + power);
// 用户输入处理(模拟)
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.println("请输入数字(输入0结束):");
int input = scanner.nextInt();
while (input != 0) {
System.out.println("您输入的数字是: " + input);
System.out.println("请继续输入数字(输入0结束):");
input = scanner.nextInt();
}
System.out.println("程序结束");
}
}
4.2 do-while循环
语法格式:
do {
执行语句 // 至少执行一次
} while (条件表达式);
特点:
- 先执行,后判断:循环体至少执行一次
- 适用于需要至少执行一次循环体的场景
示例代码:
public class DoWhileDemo {
public static void main(String[] args) {
// do-while基本用法
int i = 1;
do {
System.out.println("第" + i + "次执行");
i++;
} while (i <= 3);
// 对比while和do-while的差异
System.out.println("=== while循环 ===");
int a = 10;
while (a < 10) {
System.out.println("while循环执行"); // 不会执行
a++;
}
System.out.println("=== do-while循环 ===");
int b = 10;
do {
System.out.println("do-while循环执行"); // 会执行一次
b++;
} while (b < 10);
// 实际应用:菜单选择
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.println("0. 退出");
System.out.print("请输入选择: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("当前余额: 1000元");
break;
case 2:
System.out.println("请输入存款金额...");
break;
case 3:
System.out.println("请输入取款金额...");
break;
case 0:
System.out.println("谢谢使用,再见!");
break;
default:
System.out.println("无效选择,请重新输入");
}
} while (choice != 0);
// 生成随机数直到满足条件
java.util.Random random = new java.util.Random();
int randomNum;
int attempts = 0;
do {
randomNum = random.nextInt(100) + 1; // 1-100的随机数
attempts++;
System.out.println("第" + attempts + "次生成: " + randomNum);
} while (randomNum != 88); // 直到生成88
System.out.println("终于生成了88!总共尝试了" + attempts + "次");
}
}
4.3 for循环
语法格式:
for (初始化表达式; 条件表达式; 循环后的操作表达式) {
执行语句
}
执行流程:
- 执行初始化表达式(只执行一次)
- 判断条件表达式
- 如果为true,执行循环体
- 执行循环后的操作表达式
- 返回步骤2
- 如果为false,结束循环
基本示例:
public class ForDemo {
public static void main(String[] args) {
// 基本for循环
for (int i = 1; i <= 5; i++) {
System.out.println("第" + i + "次循环");
}
// 倒序循环
for (int i = 10; i >= 1; i--) {
System.out.println("倒数第" + (11-i) + "个数: " + i);
}
// 步长不为1的循环
for (int i = 0; i <= 20; i += 3) {
System.out.println("i = " + i);
}
// 字符循环
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
}
System.out.println();
// 计算阶乘
int n = 5;
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println(n + "! = " + factorial);
// 嵌套for循环:九九乘法表
System.out.println("九九乘法表:");
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();
}
// 数组遍历
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
// 增强for循环(for-each)
System.out.println("使用增强for循环:");
for (int num : numbers) {
System.out.println("值: " + num);
}
}
}
4.4 三种循环的比较
| 特征 | while | do-while | for |
|---|---|---|---|
| 执行次数 | 0次或多次 | 1次或多次 | 0次或多次 |
| 条件判断时机 | 循环前 | 循环后 | 循环前 |
| 适用场景 | 不确定循环次数 | 至少执行一次 | 确定循环次数 |
| 变量作用域 | 需要在外部定义 | 需要在外部定义 | 可以在内部定义 |
public class LoopComparison {
public static void main(String[] args) {
System.out.println("=== 变量作用域对比 ===");
// while循环:变量在外部定义,循环结束后仍存在
int whileVar = 0;
while (whileVar < 3) {
System.out.println("while: " + whileVar);
whileVar++;
}
System.out.println("while循环结束后,变量值: " + whileVar); // 变量仍然存在
// for循环:变量在内部定义,循环结束后自动释放
for (int forVar = 0; forVar < 3; forVar++) {
System.out.println("for: " + forVar);
}
// System.out.println(forVar); // 编译错误,变量已经不存在
System.out.println("=== 应用场景对比 ===");
// 场景1:已知循环次数 - 推荐使用for
for (int i = 0; i < 10; i++) {
// 执行10次
}
// 场景2:条件驱动的循环 - 推荐使用while
java.util.Scanner scanner = new java.util.Scanner("1 2 3 4 0");
int input = scanner.nextInt();
while (input != 0) {
System.out.println("处理: " + input);
input = scanner.nextInt();
}
// 场景3:至少执行一次 - 推荐使用do-while
boolean continueGame;
do {
System.out.println("游戏开始...");
// 游戏逻辑
continueGame = false; // 假设用户选择不继续
System.out.println("游戏结束,是否继续?");
} while (continueGame);
}
}
5. 跳转控制语句
5.1 break语句
功能: 跳出循环,结束当前循环
适用范围:
- 选择结构(switch语句)
- 循环结构(while、do-while、for)
基本使用:
public class BreakDemo {
public static void main(String[] args) {
// 在for循环中使用break
for (int i = 1; i <= 10; i++) {
if (i == 6) {
System.out.println("遇到6,跳出循环");
break;
}
System.out.println("i = " + i);
}
System.out.println("循环结束");
// 在while循环中使用break
int num = 1;
while (true) { // 无限循环
if (num > 5) {
System.out.println("num超过5,退出循环");
break;
}
System.out.println("num = " + num);
num++;
}
// 查找数组中的元素
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;
boolean found = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
System.out.println("找到目标值 " + target + " 在索引 " + i);
found = true;
break; // 找到就退出,提高效率
}
}
if (!found) {
System.out.println("未找到目标值");
}
// 在嵌套循环中,break只跳出最内层循环
System.out.println("=== 嵌套循环中的break ===");
for (int i = 1; i <= 3; i++) {
System.out.println("外层循环: i = " + i);
for (int j = 1; j <= 3; j++) {
if (j == 2) {
System.out.println("内层循环遇到j=2,跳出内层循环");
break; // 只跳出内层循环
}
System.out.println(" 内层循环: j = " + j);
}
}
}
}
5.2 continue语句
功能: 跳出本次循环,继续下一次循环
适用范围: 循环结构(while、do-while、for)
基本使用:
public class ContinueDemo {
public static void main(String[] args) {
// 在for循环中使用continue
System.out.println("=== 跳过偶数,只打印奇数 ===");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 跳过本次循环,继续下一次
}
System.out.println("奇数: " + i);
}
// 在while循环中使用continue
System.out.println("=== while循环中的continue ===");
int num = 0;
while (num < 10) {
num++;
if (num % 3 == 0) {
continue; // 跳过3的倍数
}
System.out.println("非3的倍数: " + num);
}
// 实际应用:处理数据时跳过无效值
System.out.println("=== 处理数组,跳过负数 ===");
int[] data = {5, -2, 8, -1, 10, -3, 7};
int sum = 0;
int validCount = 0;
for (int value : data) {
if (value < 0) {
System.out.println("跳过负数: " + value);
continue; // 跳过负数
}
sum += value;
validCount++;
System.out.println("累加正数: " + value + ",当前和: " + sum);
}
System.out.println("有效数据个数: " + validCount);
System.out.println("有效数据总和: " + sum);
// 在嵌套循环中使用continue
System.out.println("=== 嵌套循环中的continue ===");
for (int i = 1; i <= 3; i++) {
System.out.println("外层循环: i = " + i);
for (int j = 1; j <= 5; j++) {
if (j == 3) {
System.out.println(" 跳过 j = 3");
continue; // 跳过本次内层循环
}
System.out.println(" 内层循环: j = " + j);
}
}
}
}
5.3 带标签的break和continue
当有嵌套循环时,可以使用标签来指定跳出哪一层循环。
语法格式:
标签名: for (...) {
for (...) {
break 标签名; // 跳出指定标签的循环
continue 标签名; // 跳过指定标签的本次循环
}
}
示例代码:
public class LabelDemo {
public static void main(String[] args) {
// 使用标签的break:跳出外层循环
System.out.println("=== 带标签的break ===");
outer: for (int i = 1; i <= 3; i++) {
System.out.println("外层循环: i = " + i);
for (int j = 1; j <= 3; j++) {
System.out.println(" 内层循环: j = " + j);
if (i == 2 && j == 2) {
System.out.println(" 条件满足,跳出外层循环");
break outer; // 跳出外层循环
}
}
System.out.println("外层循环 i = " + i + " 结束");
}
System.out.println("所有循环结束");
System.out.println("\n=== 使用标签的continue ===");
outer2: for (int i = 1; i <= 3; i++) {
System.out.println("外层循环: i = " + i);
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println(" 跳过外层循环的本次迭代");
continue outer2; // 跳过外层循环的本次迭代
}
System.out.println(" 内层循环: j = " + j);
}
System.out.println("外层循环 i = " + i + " 结束");
}
// 实际应用:在二维数组中查找元素
System.out.println("\n=== 实际应用:二维数组查找 ===");
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 5;
boolean found = false;
search: for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println("检查位置[" + i + "][" + j + "] = " + matrix[i][j]);
if (matrix[i][j] == target) {
System.out.println("找到目标值 " + target + " 在位置[" + i + "][" + j + "]");
found = true;
break search; // 找到后跳出所有循环
}
}
}
if (!found) {
System.out.println("未找到目标值 " + target);
}
// 打印特殊图案:使用标签控制循环
System.out.println("\n=== 打印图案示例 ===");
pattern: for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i + j > 6) {
System.out.println();
continue pattern; // 跳到外层循环的下一次
}
System.out.print("* ");
}
}
}
}
5.4 break和continue使用总结
| 语句 | 作用 | 适用结构 | 影响范围 |
|---|---|---|---|
| break | 终止循环 | switch、循环 | 当前循环层 |
| continue | 跳过本次循环 | 循环 | 当前循环层 |
| break 标签 | 终止指定循环 | 循环 | 指定标签的循环 |
| continue 标签 | 跳过指定循环的本次迭代 | 循环 | 指定标签的循环 |
6. 流程控制最佳实践
6.1 代码可读性
public class ReadabilityDemo {
public static void main(String[] args) {
// 1. 使用有意义的变量名
int studentAge = 20;
boolean hasDriverLicense = true;
double accountBalance = 1500.50;
// 2. 合理使用空行和缩进
if (studentAge >= 18) {
System.out.println("已成年");
if (hasDriverLicense) {
System.out.println("可以独立驾车");
} else {
System.out.println("需要考取驾照");
}
}
// 3. 避免过深的嵌套
// 不好的写法
if (accountBalance > 0) {
if (accountBalance >= 100) {
if (accountBalance >= 1000) {
System.out.println("VIP客户");
} else {
System.out.println("普通客户");
}
} else {
System.out.println("余额不足");
}
} else {
System.out.println("账户异常");
}
// 更好的写法
if (accountBalance <= 0) {
System.out.println("账户异常");
return;
}
if (accountBalance < 100) {
System.out.println("余额不足");
} else if (accountBalance >= 1000) {
System.out.println("VIP客户");
} else {
System.out.println("普通客户");
}
}
}
6.2 性能优化
public class PerformanceDemo {
public static void main(String[] args) {
// 1. 减少循环内的计算
String[] words = {"hello", "world", "java", "programming"};
// 不好的写法:每次都计算length
for (int i = 0; i < words.length; i++) {
// 如果words.length是复杂计算,会影响性能
}
// 更好的写法:缓存长度
int length = words.length;
for (int i = 0; i < length; i++) {
// 性能更好
}
// 2. 合理使用break和continue
int[] numbers = new int[1000];
// 初始化数组
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i;
}
// 查找特定值:找到后立即退出
int target = 500;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
System.out.println("找到目标值: " + target);
break; // 提高效率
}
}
// 3. 选择合适的循环类型
// 数组遍历:推荐使用增强for循环
for (int num : numbers) {
if (num % 2 == 0) {
// 处理偶数
}
}
}
}
6.3 常见陷阱和解决方案
public class CommonTrapsDemo {
public static void main(String[] args) {
// 陷阱1:浮点数比较
double a = 0.1 + 0.2;
double b = 0.3;
// 错误写法
if (a == b) { // 可能为false
System.out.println("相等");
} else {
System.out.println("不相等");
}
// 正确写法
double epsilon = 1e-10;
if (Math.abs(a - b) < epsilon) {
System.out.println("相等");
} else {
System.out.println("不相等");
}
// 陷阱2:字符串比较
String str1 = new String("hello");
String str2 = new String("hello");
// 错误写法
if (str1 == str2) { // false
System.out.println("字符串相等");
}
// 正确写法
if (str1.equals(str2)) { // true
System.out.println("字符串相等");
}
// 陷阱3:空指针检查
String nullStr = null;
// 错误写法
// if (nullStr.equals("test")) { // NullPointerException
// System.out.println("匹配");
// }
// 正确写法
if (nullStr != null && nullStr.equals("test")) {
System.out.println("匹配");
}
// 或者使用Objects.equals(推荐)
if (java.util.Objects.equals(nullStr, "test")) {
System.out.println("匹配");
}
// 陷阱4:修改循环变量
for (int i = 0; i < 10; i++) {
if (i == 5) {
i += 2; // 在循环体内修改循环变量,可能导致逻辑错误
}
System.out.println("i = " + i);
}
}
}
7. 实际应用案例
7.1 综合案例:学生成绩管理
public class StudentGradeManager {
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print("请输入学生数量: ");
int studentCount = scanner.nextInt();
double[] grades = new double[studentCount];
double sum = 0;
double maxGrade = Double.MIN_VALUE;
double minGrade = Double.MAX_VALUE;
// 输入成绩
for (int i = 0; i < studentCount; i++) {
do {
System.out.print("请输入第" + (i + 1) + "个学生的成绩(0-100): ");
grades[i] = scanner.nextDouble();
if (grades[i] < 0 || grades[i] > 100) {
System.out.println("成绩必须在0-100之间,请重新输入!");
}
} while (grades[i] < 0 || grades[i] > 100);
sum += grades[i];
maxGrade = Math.max(maxGrade, grades[i]);
minGrade = Math.min(minGrade, grades[i]);
}
// 计算平均分
double average = sum / studentCount;
// 统计等级分布
int excellentCount = 0, goodCount = 0, passCount = 0, failCount = 0;
for (double grade : grades) {
if (grade >= 90) {
excellentCount++;
} else if (grade >= 80) {
goodCount++;
} else if (grade >= 60) {
passCount++;
} else {
failCount++;
}
}
// 输出统计结果
System.out.println("\n=== 成绩统计结果 ===");
System.out.printf("平均分: %.2f\n", average);
System.out.printf("最高分: %.1f\n", maxGrade);
System.out.printf("最低分: %.1f\n", minGrade);
System.out.println("\n等级分布:");
System.out.println("优秀(90-100): " + excellentCount + "人");
System.out.println("良好(80-89): " + goodCount + "人");
System.out.println("及格(60-79): " + passCount + "人");
System.out.println("不及格(0-59): " + failCount + "人");
// 显示详细成绩
System.out.println("\n详细成绩单:");
for (int i = 0; i < grades.length; i++) {
String level;
if (grades[i] >= 90) {
level = "优秀";
} else if (grades[i] >= 80) {
level = "良好";
} else if (grades[i] >= 60) {
level = "及格";
} else {
level = "不及格";
}
System.out.printf("学生%d: %.1f分 - %s\n", (i + 1), grades[i], level);
}
}
}
7.2 实用工具:简单计算器
public class SimpleCalculator {
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
boolean continueCalculating = true;
System.out.println("=== 简单计算器 ===");
while (continueCalculating) {
System.out.println("\n请选择操作:");
System.out.println("1. 加法 (+)");
System.out.println("2. 减法 (-)");
System.out.println("3. 乘法 (*)");
System.out.println("4. 除法 (/)");
System.out.println("5. 求余 (%)");
System.out.println("0. 退出");
System.out.print("请输入选择: ");
int choice = scanner.nextInt();
if (choice == 0) {
System.out.println("感谢使用计算器,再见!");
break;
}
if (choice < 1 || choice > 5) {
System.out.println("无效选择,请重新输入!");
continue;
}
System.out.print("请输入第一个数: ");
double num1 = scanner.nextDouble();
System.out.print("请输入第二个数: ");
double num2 = scanner.nextDouble();
double result = 0;
String operation = "";
boolean validOperation = true;
switch (choice) {
case 1:
result = num1 + num2;
operation = "+";
break;
case 2:
result = num1 - num2;
operation = "-";
break;
case 3:
result = num1 * num2;
operation = "*";
break;
case 4:
if (num2 == 0) {
System.out.println("错误:除数不能为0!");
validOperation = false;
} else {
result = num1 / num2;
operation = "/";
}
break;
case 5:
if (num2 == 0) {
System.out.println("错误:除数不能为0!");
validOperation = false;
} else {
result = num1 % num2;
operation = "%";
}
break;
}
if (validOperation) {
System.out.printf("计算结果: %.2f %s %.2f = %.2f\n",
num1, operation, num2, result);
}
System.out.print("\n是否继续计算?(y/n): ");
String continueChoice = scanner.next();
continueCalculating = continueChoice.equalsIgnoreCase("y") ||
continueChoice.equalsIgnoreCase("yes");
}
scanner.close();
}
}
8. 总结
8.1 核心要点
-
判断结构(if语句):
- 三种格式适用于不同场景
- 注意if-else if与多个if的区别
- 避免过深的嵌套
-
选择结构(switch语句):
- 支持byte、short、int、char、String、枚举类型
- 理解case穿透特性
- 合理使用break语句
-
循环结构:
- while:条件驱动,可能不执行
- do-while:至少执行一次
- for:已知次数的循环,变量作用域更小
-
跳转控制:
- break:跳出循环或switch
- continue:跳过本次循环
- 标签:精确控制跳转位置
8.2 选择指南
| 场景 | 推荐语句 | 理由 |
|---|---|---|
| 简单条件判断 | if-else | 直观易懂 |
| 多个等值选择 | switch | 效率高,结构清晰 |
| 已知循环次数 | for | 变量作用域小,代码紧凑 |
| 条件驱动循环 | while | 逻辑清晰 |
| 至少执行一次 | do-while | 符合业务逻辑 |
| 复杂嵌套控制 | 标签 + break/continue | 精确控制 |
8.3 最佳实践
- 代码可读性:使用有意义的变量名,合理的缩进和空行
- 性能优化:减少循环内的重复计算,合理使用break/continue
- 避免陷阱:注意浮点数比较、字符串比较、空指针检查
- 选择合适的结构:根据业务逻辑选择最合适的控制语句
- 异常处理:在循环和判断中加入必要的异常处理逻辑
掌握Java流程控制语句是编程的基础,正确理解和使用这些语句可以编写出逻辑清晰、高效的程序。在实际开发中,要根据具体场景选择合适的控制结构,同时注意代码的可读性和性能。
本文详细介绍了Java程序流程控制的所有语句类型、语法格式、执行特点和实际应用,希望对Java编程学习有所帮助。