前言

流程控制是程序设计的核心概念之一,它决定了程序的执行路径和逻辑结构。Java提供了丰富的流程控制语句,包括条件语句、循环语句和跳转语句,这些语句让程序能够根据不同的条件执行不同的操作,实现复杂的业务逻辑。本文将深入探讨Java中的各种流程控制语句,帮助读者掌握程序控制的精髓。

流程控制概述

程序的执行流程通常分为三种基本结构:顺序结构、选择结构和循环结构。Java的流程控制语句正是实现这些结构的工具。

graph TD
    A[程序流程控制] --> B[顺序结构]
    A --> C[选择结构]
    A --> D[循环结构]
    A --> E[跳转控制]
    
    B --> F[语句按顺序执行]
    
    C --> G[条件语句]
    G --> H[if-else]
    G --> I[switch-case]
    
    D --> J[循环语句]
    J --> K[for循环]
    J --> L[while循环]
    J --> M[do-while循环]
    J --> N[增强for循环]
    
    E --> O[跳转语句]
    O --> P[break]
    O --> Q[continue]
    O --> R[return]

条件语句

条件语句允许程序根据特定条件选择不同的执行路径,是实现程序逻辑分支的重要工具。

if-else语句

if-else语句是最基本的条件语句,提供了灵活的条件判断机制。

基本if语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class ConditionalStatements {
public void demonstrateBasicIf() {
int score = 85;

// 基本if语句
if (score >= 60) {
System.out.println("及格了!");
}

// if-else语句
if (score >= 90) {
System.out.println("优秀");
} else {
System.out.println("良好或及格");
}

// 多重if-else语句
if (score >= 90) {
System.out.println("等级:A");
} else if (score >= 80) {
System.out.println("等级:B");
} else if (score >= 70) {
System.out.println("等级:C");
} else if (score >= 60) {
System.out.println("等级:D");
} else {
System.out.println("等级:F");
}
}
}

复杂条件判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public void demonstrateComplexConditions() {
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = true;
String weather = "sunny";

// 复合条件
if (age >= 18 && hasLicense && hasInsurance) {
System.out.println("可以驾驶汽车");
}

// 嵌套if语句
if (age >= 18) {
if (hasLicense) {
if (hasInsurance) {
if (weather.equals("sunny") || weather.equals("cloudy")) {
System.out.println("今天适合开车出行");
} else {
System.out.println("天气不佳,建议谨慎驾驶");
}
} else {
System.out.println("需要购买保险");
}
} else {
System.out.println("需要获得驾驶执照");
}
} else {
System.out.println("年龄不足,无法驾驶");
}

// 使用逻辑运算符简化嵌套
if (age >= 18 && hasLicense && hasInsurance &&
(weather.equals("sunny") || weather.equals("cloudy"))) {
System.out.println("所有条件满足,可以安全驾驶");
}
}

if语句的最佳实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class IfBestPractices {

// 避免深度嵌套的技巧
public String evaluateStudentGrade(int score, boolean hasExtraCredit,
boolean isPerfectAttendance) {
// 使用早期返回减少嵌套
if (score < 0 || score > 100) {
return "无效分数";
}

if (score < 60) {
return "不及格";
}

// 计算最终分数
int finalScore = score;
if (hasExtraCredit) {
finalScore += 5;
}
if (isPerfectAttendance) {
finalScore += 3;
}

// 确保不超过100分
finalScore = Math.min(finalScore, 100);

// 返回等级
if (finalScore >= 95) return "A+";
if (finalScore >= 90) return "A";
if (finalScore >= 85) return "B+";
if (finalScore >= 80) return "B";
if (finalScore >= 75) return "C+";
if (finalScore >= 70) return "C";
if (finalScore >= 65) return "D+";
if (finalScore >= 60) return "D";
return "F";
}

// 使用方法提取复杂条件
public boolean canAccessSystem(User user) {
return isValidUser(user) &&
hasRequiredPermissions(user) &&
isWithinBusinessHours() &&
!isSystemMaintenance();
}

private boolean isValidUser(User user) {
return user != null && user.isActive() && !user.isLocked();
}

private boolean hasRequiredPermissions(User user) {
return user.hasRole("USER") || user.hasRole("ADMIN");
}

private boolean isWithinBusinessHours() {
// 检查是否在营业时间内
return true; // 简化实现
}

private boolean isSystemMaintenance() {
// 检查系统是否在维护中
return false; // 简化实现
}
}

switch-case语句

switch语句提供了一种简洁的多路分支选择机制,特别适用于基于单个变量值的多种情况判断。

flowchart TD
    A[switch表达式] --> B{case value1}
    A --> C{case value2}
    A --> D{case value3}
    A --> E{default}
    
    B --> F[执行代码块1]
    C --> G[执行代码块2]
    D --> H[执行代码块3]
    E --> I[执行默认代码块]
    
    F --> J[break或fall-through]
    G --> J
    H --> J
    I --> J

基本switch语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
public class SwitchStatements {
public void demonstrateBasicSwitch() {
int dayOfWeek = 3;
String dayName;

switch (dayOfWeek) {
case 1:
dayName = "星期一";
break;
case 2:
dayName = "星期二";
break;
case 3:
dayName = "星期三";
break;
case 4:
dayName = "星期四";
break;
case 5:
dayName = "星期五";
break;
case 6:
dayName = "星期六";
break;
case 7:
dayName = "星期日";
break;
default:
dayName = "无效的星期";
break;
}

System.out.println("今天是:" + dayName);
}

// 支持的数据类型演示
public void demonstrateSwitchTypes() {
// byte, short, int, char
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("优秀");
break;
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("中等");
break;
default:
System.out.println("其他等级");
}

// 字符串(Java 7+)
String season = "春天";
switch (season) {
case "春天":
System.out.println("万物复苏");
break;
case "夏天":
System.out.println("绿意盎然");
break;
case "秋天":
System.out.println("硕果累累");
break;
case "冬天":
System.out.println("雪花飞舞");
break;
}

// 枚举类型
Day today = Day.MONDAY;
switch (today) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
System.out.println("工作日");
break;
case SATURDAY:
case SUNDAY:
System.out.println("周末");
break;
}
}

enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
}

fall-through特性和分组case

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public void demonstrateFallThrough() {
int month = 12;
String season;

switch (month) {
case 12:
case 1:
case 2:
season = "冬季";
break;
case 3:
case 4:
case 5:
season = "春季";
break;
case 6:
case 7:
case 8:
season = "夏季";
break;
case 9:
case 10:
case 11:
season = "秋季";
break;
default:
season = "无效月份";
}

System.out.println(month + "月属于" + season);

// 有意的fall-through示例
int score = 85;
System.out.print("成绩" + score + "分,评价:");
switch (score / 10) {
case 10:
case 9:
System.out.print("优秀");
break;
case 8:
System.out.print("良好");
break;
case 7:
System.out.print("中等");
break;
case 6:
System.out.print("及格");
break;
default:
System.out.print("不及格");
}
System.out.println();
}

Java 14+ 的switch表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Java 14+新特性:switch表达式
public void demonstrateSwitchExpressions() {
int dayOfWeek = 3;

// 使用箭头语法的switch表达式
String dayType = switch (dayOfWeek) {
case 1, 2, 3, 4, 5 -> "工作日";
case 6, 7 -> "周末";
default -> "无效日期";
};

// 带有代码块的switch表达式
String activity = switch (dayOfWeek) {
case 1 -> {
System.out.println("周一,新的开始");
yield "开会";
}
case 2, 3, 4 -> "工作";
case 5 -> {
System.out.println("周五,准备周末");
yield "整理工作";
}
case 6, 7 -> "休息";
default -> "未知";
};

System.out.println("今天是" + dayType + ",主要活动:" + activity);
}

循环语句

循环语句允许程序重复执行一段代码,直到满足某个终止条件。Java提供了多种循环结构。

for循环

for循环是最常用的循环结构,特别适合已知循环次数的情况。

graph LR
    A[初始化] --> B[条件判断]
    B --> C{条件为真?}
    C -->|是| D[执行循环体]
    D --> E[更新表达式]
    E --> B
    C -->|否| F[结束循环]

标准for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class ForLoops {
public void demonstrateBasicFor() {
// 基本for循环
System.out.println("正向遍历:");
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
System.out.println();

// 反向遍历
System.out.println("反向遍历:");
for (int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();

// 步长为2的循环
System.out.println("奇数:");
for (int i = 1; i <= 10; i += 2) {
System.out.print(i + " ");
}
System.out.println();

// 多个变量的for循环
System.out.println("多变量循环:");
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i=" + i + ", j=" + j);
}
}

// 嵌套for循环
public void demonstrateNestedFor() {
// 打印乘法表
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();
}

// 打印图案
System.out.println("\n星号三角形:");
int rows = 5;
for (int i = 1; i <= rows; i++) {
// 打印空格
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// 打印星号
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}

增强for循环(for-each)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public void demonstrateEnhancedFor() {
// 数组遍历
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("数组遍历:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();

// 集合遍历
List<String> fruits = Arrays.asList("苹果", "香蕉", "橙子", "葡萄");
System.out.println("集合遍历:");
for (String fruit : fruits) {
System.out.println("我喜欢" + fruit);
}

// 二维数组遍历
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("二维数组遍历:");
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + "\t");
}
System.out.println();
}

// 字符串字符遍历
String text = "Hello";
System.out.println("字符串字符遍历:");
for (char c : text.toCharArray()) {
System.out.print(c + " ");
}
System.out.println();
}

while循环

while循环适用于条件判断在循环开始之前进行的情况。

基本while循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class WhileLoops {
public void demonstrateBasicWhile() {
// 基本while循环
int count = 1;
System.out.println("基本while循环:");
while (count <= 5) {
System.out.print(count + " ");
count++;
}
System.out.println();

// 条件复杂的while循环
int sum = 0;
int num = 1;
while (sum < 100) {
sum += num;
num++;
}
System.out.println("累加到超过100的最小和: " + sum);
System.out.println("使用的数字个数: " + (num - 1));
}

// 实际应用示例
public void demonstrateWhileApplications() {
// 用户输入验证(模拟)
Scanner scanner = new Scanner(System.in);
int userInput = -1;

System.out.println("请输入1-10之间的数字:");
while (userInput < 1 || userInput > 10) {
System.out.print("输入无效,请重新输入(1-10): ");
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
} else {
scanner.next(); // 清除无效输入
}
}
System.out.println("您输入的有效数字是: " + userInput);

// 数字处理直到满足条件
int number = 12345;
int digitCount = 0;
int temp = number;

while (temp > 0) {
temp /= 10;
digitCount++;
}
System.out.println("数字 " + number + " 有 " + digitCount + " 位");

// 查找最大公约数
int a = 48, b = 18;
int originalA = a, originalB = b;
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
System.out.println(originalA + " 和 " + originalB + " 的最大公约数是: " + a);
}
}

do-while循环

do-while循环保证循环体至少执行一次,适用于需要先执行后判断的场景。

graph LR
    A[开始] --> B[执行循环体]
    B --> C[条件判断]
    C --> D{条件为真?}
    D -->|是| B
    D -->|否| E[结束循环]

do-while循环示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public class DoWhileLoops {
public void demonstrateDoWhile() {
// 基本do-while循环
int i = 1;
System.out.println("do-while循环:");
do {
System.out.print(i + " ");
i++;
} while (i <= 5);
System.out.println();

// 即使条件一开始就为false,也会执行一次
int j = 10;
System.out.println("条件一开始就为false的情况:");
do {
System.out.println("执行了一次,j = " + j);
j++;
} while (j < 10);
}

// 菜单系统示例
public void demonstrateMenuSystem() {
Scanner scanner = new 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("4. 修改数据");
System.out.println("0. 退出系统");
System.out.print("请选择操作 (0-4): ");

choice = scanner.nextInt();

switch (choice) {
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 0:
System.out.println("感谢使用,再见!");
break;
default:
System.out.println("无效选择,请重新输入!");
}
} while (choice != 0);
}

// 游戏循环示例
public void demonstrateGameLoop() {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
boolean playAgain;

do {
// 生成随机数字
int secretNumber = random.nextInt(100) + 1;
int attempts = 0;
int guess;

System.out.println("\n=== 猜数字游戏 ===");
System.out.println("我想了一个1-100之间的数字,你能猜到吗?");

do {
System.out.print("请输入你的猜测: ");
guess = scanner.nextInt();
attempts++;

if (guess < secretNumber) {
System.out.println("太小了!");
} else if (guess > secretNumber) {
System.out.println("太大了!");
} else {
System.out.println("恭喜!你用 " + attempts + " 次就猜中了!");
}
} while (guess != secretNumber);

System.out.print("还想再玩一次吗?(y/n): ");
playAgain = scanner.next().toLowerCase().startsWith("y");

} while (playAgain);

System.out.println("游戏结束,谢谢游玩!");
}
}

跳转语句

跳转语句改变程序的正常执行流程,提供了在特定条件下跳出循环或方法的机制。

break语句

break语句用于跳出当前循环或switch语句。

graph TD
    A[循环开始] --> B[条件判断]
    B --> C{满足break条件?}
    C -->|是| D[执行break]
    D --> E[跳出循环]
    C -->|否| F[继续执行]
    F --> G[循环体其余部分]
    G --> H[循环更新]
    H --> B

break的使用场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class BreakStatements {
public void demonstrateBasicBreak() {
// 在for循环中使用break
System.out.println("查找第一个偶数:");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println("找到第一个偶数: " + i);
break; // 跳出循环
}
System.out.println("检查数字: " + i);
}

// 在while循环中使用break
System.out.println("\n无限循环中的break:");
int count = 0;
while (true) {
count++;
System.out.println("计数: " + count);
if (count >= 5) {
System.out.println("达到限制,退出循环");
break;
}
}
}

// 标签化的break
public void demonstrateLabeledBreak() {
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; // 跳出到outer标签处
}
}
System.out.println("外层循环结束");
}
System.out.println("循环完全结束");
}

// 在数组搜索中使用break
public void demonstrateSearchWithBreak() {
int[] numbers = {3, 7, 1, 9, 4, 6, 8, 2, 5};
int target = 9;
boolean found = false;
int index = -1;

System.out.println("在数组中搜索 " + target + ":");
for (int i = 0; i < numbers.length; i++) {
System.out.println("检查索引 " + i + ": " + numbers[i]);
if (numbers[i] == target) {
found = true;
index = i;
System.out.println("找到目标值!");
break; // 找到后立即退出
}
}

if (found) {
System.out.println("目标值 " + target + " 在索引 " + index + " 处");
} else {
System.out.println("未找到目标值 " + target);
}
}
}

continue语句

continue语句跳过当前循环迭代的剩余部分,直接进入下一次迭代。

continue的使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
public class ContinueStatements {
public void demonstrateBasicContinue() {
// 跳过偶数,只打印奇数
System.out.println("只打印奇数:");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 跳过偶数
}
System.out.print(i + " ");
}
System.out.println();

// 在while循环中使用continue
System.out.println("\n跳过负数和零:");
int[] numbers = {5, -2, 8, 0, -1, 3, 7};
for (int num : numbers) {
if (num <= 0) {
System.out.println("跳过: " + num);
continue;
}
System.out.println("处理: " + num + ", 平方: " + (num * num));
}
}

// 标签化的continue
public void demonstrateLabeledContinue() {
System.out.println("嵌套循环中的标签continue:");

outer:
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 outer; // 跳过外层循环的当前迭代
}
System.out.println(" 内层循环: j = " + j);
}
System.out.println("内层循环结束");
}
}

// 数据处理中的continue应用
public void demonstrateDataProcessing() {
String[] userData = {"alice@email.com", "", "bob@email.com",
"invalid-email", "charlie@email.com", null};

System.out.println("处理用户邮箱数据:");
int validCount = 0;
int skippedCount = 0;

for (String email : userData) {
// 跳过无效数据
if (email == null || email.isEmpty()) {
skippedCount++;
System.out.println("跳过空邮箱");
continue;
}

if (!email.contains("@") || !email.contains(".")) {
skippedCount++;
System.out.println("跳过无效邮箱: " + email);
continue;
}

// 处理有效邮箱
validCount++;
System.out.println("处理有效邮箱: " + email);
}

System.out.println("总计: " + validCount + " 个有效邮箱, " +
skippedCount + " 个跳过");
}
}

return语句

return语句用于从方法中返回值并结束方法的执行。

return语句的应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
public class ReturnStatements {

// 基本return用法
public int findFirstEven(int[] numbers) {
for (int num : numbers) {
if (num % 2 == 0) {
return num; // 找到第一个偶数就返回
}
}
return -1; // 没找到返回-1
}

// 多个return语句
public String categorizeAge(int age) {
if (age < 0) {
return "无效年龄";
}
if (age < 13) {
return "儿童";
}
if (age < 20) {
return "青少年";
}
if (age < 60) {
return "成年人";
}
return "老年人";
}

// 在void方法中使用return
public void processNumber(int number) {
if (number < 0) {
System.out.println("错误:数字不能为负数");
return; // 提前结束方法
}

if (number == 0) {
System.out.println("数字为零,无需处理");
return;
}

// 正常处理逻辑
System.out.println("处理数字: " + number);
System.out.println("平方: " + (number * number));
System.out.println("立方: " + (number * number * number));
}

// 复杂条件下的return
public boolean validateUser(String username, String password, boolean isActive) {
// 验证用户名
if (username == null || username.trim().isEmpty()) {
System.out.println("用户名不能为空");
return false;
}

if (username.length() < 3) {
System.out.println("用户名长度至少3个字符");
return false;
}

// 验证密码
if (password == null || password.length() < 8) {
System.out.println("密码长度至少8个字符");
return false;
}

// 验证账户状态
if (!isActive) {
System.out.println("账户已被禁用");
return false;
}

System.out.println("用户验证成功");
return true;
}

// 演示方法
public void demonstrateReturn() {
int[] numbers = {1, 3, 7, 8, 9, 12};
int firstEven = findFirstEven(numbers);
System.out.println("第一个偶数: " + firstEven);

System.out.println("年龄分类: " + categorizeAge(25));

processNumber(-5);
processNumber(0);
processNumber(4);

validateUser("john", "password123", true);
validateUser("ab", "123", false);
}
}

流程控制的综合应用

复杂逻辑处理示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
public class ComplexFlowControl {

// 计算器程序
public void calculatorDemo() {
Scanner scanner = new Scanner(System.in);
boolean continueCalculation = true;

System.out.println("=== 简单计算器 ===");

while (continueCalculation) {
try {
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 validOperation = true;

switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
System.out.println("错误:除数不能为零!");
validOperation = false;
result = 0;
} else {
result = num1 / num2;
}
break;
case '%':
if (num2 == 0) {
System.out.println("错误:模数不能为零!");
validOperation = false;
result = 0;
} else {
result = num1 % num2;
}
break;
default:
System.out.println("错误:无效的运算符!");
validOperation = false;
result = 0;
}

if (validOperation) {
System.out.printf("结果: %.2f %c %.2f = %.2f%n",
num1, operator, num2, result);
}

System.out.print("继续计算吗?(y/n): ");
String choice = scanner.next();
continueCalculation = choice.toLowerCase().startsWith("y");

} catch (Exception e) {
System.out.println("输入错误,请输入有效的数字!");
scanner.nextLine(); // 清除错误输入
}
}

System.out.println("计算器程序结束,谢谢使用!");
}

// 学生成绩管理系统
public void gradeManagementSystem() {
Scanner scanner = new Scanner(System.in);
List<Student> students = new ArrayList<>();

while (true) {
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();
scanner.nextLine(); // 消费换行符

switch (choice) {
case 1:
addStudent(scanner, students);
break;
case 2:
displayAllStudents(students);
break;
case 3:
searchStudent(scanner, students);
break;
case 4:
calculateAverageScore(students);
break;
case 5:
displayGradeStatistics(students);
break;
case 0:
System.out.println("程序退出,再见!");
return;
default:
System.out.println("无效选择,请重新输入!");
}
}
}

private void addStudent(Scanner scanner, List<Student> students) {
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之间!");
return;
}

students.add(new Student(name, score));
System.out.println("学生添加成功!");
}

private void displayAllStudents(List<Student> students) {
if (students.isEmpty()) {
System.out.println("暂无学生记录!");
return;
}

System.out.println("\n所有学生信息:");
System.out.println("姓名\t\t分数\t等级");
System.out.println("------------------------");
for (Student student : students) {
System.out.printf("%-10s\t%d\t%s%n",
student.getName(),
student.getScore(),
getGrade(student.getScore()));
}
}

private void searchStudent(Scanner scanner, List<Student> students) {
System.out.print("输入要查找的学生姓名: ");
String name = scanner.nextLine();

for (Student student : students) {
if (student.getName().equalsIgnoreCase(name)) {
System.out.printf("找到学生: %s, 分数: %d, 等级: %s%n",
student.getName(),
student.getScore(),
getGrade(student.getScore()));
return;
}
}
System.out.println("未找到该学生!");
}

private void calculateAverageScore(List<Student> students) {
if (students.isEmpty()) {
System.out.println("暂无学生记录!");
return;
}

double sum = 0;
for (Student student : students) {
sum += student.getScore();
}

double average = sum / students.size();
System.out.printf("平均分: %.2f%n", average);
}

private void displayGradeStatistics(List<Student> students) {
if (students.isEmpty()) {
System.out.println("暂无学生记录!");
return;
}

int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0;

for (Student student : students) {
char grade = getGrade(student.getScore()).charAt(0);
switch (grade) {
case 'A': aCount++; break;
case 'B': bCount++; break;
case 'C': cCount++; break;
case 'D': dCount++; break;
case 'F': fCount++; break;
}
}

System.out.println("\n成绩统计:");
System.out.println("A级: " + aCount + " 人");
System.out.println("B级: " + bCount + " 人");
System.out.println("C级: " + cCount + " 人");
System.out.println("D级: " + dCount + " 人");
System.out.println("F级: " + fCount + " 人");
}

private String getGrade(int score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F";
}

// 简单的Student类
static class Student {
private String name;
private int score;

public Student(String name, int score) {
this.name = name;
this.score = score;
}

public String getName() { return name; }
public int getScore() { return score; }
}
}

总结

Java的流程控制语句是构建程序逻辑的重要工具。通过本文的学习,我们深入了解了:

  1. 条件语句:if-else和switch-case语句提供了灵活的分支控制
  2. 循环语句:for、while和do-while循环实现了重复执行的逻辑
  3. 跳转语句:break、continue和return语句控制程序的执行流程

掌握这些流程控制语句的正确使用方法,对于编写清晰、高效的Java程序至关重要。在实际开发中,建议:

  • 选择合适的控制结构来表达程序逻辑
  • 避免过深的嵌套,保持代码可读性
  • 合理使用跳转语句来简化复杂逻辑
  • 注意边界条件和异常情况的处理
  • 编写易于理解和维护的代码

通过熟练掌握这些流程控制技巧,您将能够构建更加复杂和实用的Java应用程序。

参考资料