Java流程控制语句

流程控制语句

流程控制语句是编程中用于控制程序执行流程的结构,Java 提供了多种流程控制语句。

条件语句

1. if 语句

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

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

// if-else 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("E");
}

2. switch 语句

int day = 3;
String dayName;

switch (day) {
    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 = "无效的天数";
}

System.out.println(dayName); // 输出: 星期三

3. 增强型 switch (Java 14+)

// 使用箭头语法
int month = 5;
String season = switch (month) {
    case 12, 1, 2 -> "冬季";
    case 3, 4, 5 -> "春季";
    case 6, 7, 8 -> "夏季";
    case 9, 10, 11 -> "秋季";
    default -> "无效月份";
};

// 使用 yield 返回值
String result = switch (day) {
    case 1, 2, 3, 4, 5 -> {
        yield "工作日";
    }
    case 6, 7 -> {
        yield "周末";
    }
    default -> {
        yield "无效";
    }
};

循环语句

1. for 循环

// 基本 for 循环
for (int i = 1; i <= 5; i++) {
    System.out.println("循环次数: " + i);
}

// 输出数组元素
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
    System.out.println("元素: " + numbers[i]);
}

2. 增强型 for 循环 (foreach)

// 遍历数组
String[] fruits = {"苹果", "香蕉", "橙子"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

// 遍历集合
List<String> colors = Arrays.asList("红色", "绿色", "蓝色");
for (String color : colors) {
    System.out.println(color);
}

3. while 循环

// 基本 while 循环
int count = 1;
while (count <= 5) {
    System.out.println("计数: " + count);
    count++;
}

// 使用 while 处理用户输入
Scanner scanner = new Scanner(System.in);
String input;
while (!(input = scanner.nextLine()).equals("exit")) {
    System.out.println("你输入了: " + input);
}

4. do-while 循环

// do-while 循环(至少执行一次)
int number = 1;
do {
    System.out.println("数字: " + number);
    number++;
} while (number <= 5);

// 菜单选择示例
Scanner scanner = new Scanner(System.in);
int choice;
do {
    System.out.println("1. 选项一");
    System.out.println("2. 选项二");
    System.out.println("0. 退出");
    System.out.print("请选择: ");
    choice = scanner.nextInt();
    
    switch (choice) {
        case 1 -> System.out.println("执行选项一");
        case 2 -> System.out.println("执行选项二");
        case 0 -> System.out.println("退出程序");
        default -> System.out.println("无效选择");
    }
} while (choice != 0);

跳转语句

1. break 语句

// 跳出循环
for (int i = 1; i <= 10; i++) {
    if (i == 6) {
        break; // 当 i=6 时跳出循环
    }
    System.out.println(i);
}

// 带标签的 break
outerLoop:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break outerLoop; // 跳出外层循环
        }
        System.out.println("i=" + i + ", j=" + j);
    }
}

2. continue 语句

// 跳过当前迭代
for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue; // 跳过 i=3 的情况
    }
    System.out.println(i);
}

// 带标签的 continue
outerLoop:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            continue outerLoop; // 继续外层循环的下一次迭代
        }
        System.out.println("i=" + i + ", j=" + j);
    }
}

3. return 语句

public class ReturnExample {
    
    // 从方法返回值
    public static int add(int a, int b) {
        return a + b;
    }
    
    // 提前返回
    public static String checkNumber(int number) {
        if (number < 0) {
            return "负数";
        }
        if (number == 0) {
            return "零";
        }
        return "正数";
    }
    
    public static void main(String[] args) {
        int result = add(5, 3);
        System.out.println("5 + 3 = " + result);
        
        System.out.println("检查 -5: " + checkNumber(-5));
        System.out.println("检查 0: " + checkNumber(0));
        System.out.println("检查 10: " + checkNumber(10));
    }
}

综合示例

示例 1: 成绩等级判断

public class GradeSystem {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        while (true) {
            System.out.print("请输入成绩 (0-100, 输入-1退出): ");
            int score = scanner.nextInt();
            
            if (score == -1) {
                System.out.println("程序结束");
                break;
            }
            
            if (score < 0 || score > 100) {
                System.out.println("成绩无效,请输入0-100之间的数字");
                continue;
            }
            
            String grade;
            if (score >= 90) {
                grade = "A";
            } else if (score >= 80) {
                grade = "B";
            } else if (score >= 70) {
                grade = "C";
            } else if (score >= 60) {
                grade = "D";
            } else {
                grade = "E";
            }
            
            System.out.println("成绩等级: " + grade);
        }
        
        scanner.close();
    }
}

示例 2: 素数判断

public class PrimeNumberChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("请输入一个整数: ");
        int number = scanner.nextInt();
        
        if (isPrime(number)) {
            System.out.println(number + " 是素数");
        } else {
            System.out.println(number + " 不是素数");
        }
        
        // 打印 1-100 的所有素数
        System.out.println("1-100 的素数:");
        for (int i = 2; i <= 100; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }
        
        scanner.close();
    }
    
    public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }
        
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }
        
        return true;
    }
}

示例 3: 九九乘法表

public class MultiplicationTable {
    public static void main(String[] args) {
        // 使用嵌套循环打印九九乘法表
        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另一种格式:");
        // 使用 while 循环
        int row = 1;
        while (row <= 9) {
            int col = 1;
            while (col <= row) {
                System.out.print(col + "×" + row + "=" + (row * col) + "\t");
                col++;
            }
            System.out.println();
            row++;
        }
    }
}

要点总结

  1. 条件语句: 用于基于条件执行不同的代码块

    • if-else: 适合复杂的条件判断

    • switch: 适合多分支选择,值比较

  2. 循环语句: 用于重复执行代码块

    • for: 适合已知循环次数的情况

    • while: 适合未知循环次数,先判断后执行

    • do-while: 至少执行一次,先执行后判断

  3. 跳转语句: 用于改变程序执行流程

    • break: 跳出循环或switch语句

    • continue: 跳过当前循环迭代

    • return: 从方法返回

  4. 最佳实践:

    • 避免深层嵌套

    • 使用增强型for循环遍历集合

    • 在switch语句中不要忘记break

    • 合理使用循环标签

这些流程控制语句是Java编程的基础,熟练掌握它们对于编写高效、可读性强的代码至关重要。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值