switch 关键字

概述

switch 关键字用于创建多路分支结构,根据表达式的值选择执行相应的分支。

语法格式

switch (表达式) {
    case1:
        // 代码块1
        break;
    case2:
        // 代码块2
        break;
    default:
        // 默认代码块
        break;
}

基本用法

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;

        switch (day) {
            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:
            case 7:
                System.out.println("周末");
                break;
            default:
                System.out.println("无效的天数");
                break;
        }

        // 字符switch
        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("需要努力");
        }
    }
}

字符串switch(Java 7+)

public class StringSwitchExample {
    public static void main(String[] args) {
        String fruit = "apple";

        switch (fruit) {
            case "apple":
                System.out.println("苹果");
                break;
            case "banana":
                System.out.println("香蕉");
                break;
            case "orange":
                System.out.println("橙子");
                break;
            default:
                System.out.println("未知水果");
        }
    }
}

Switch表达式(Java 14+)

public class SwitchExpressionExample {
    public static void main(String[] args) {
        int day = 3;

        // 传统switch表达式
        String dayName = switch (day) {
            case 1 -> "星期一";
            case 2 -> "星期二";
            case 3 -> "星期三";
            case 4 -> "星期四";
            case 5 -> "星期五";
            case 6, 7 -> "周末";
            default -> "无效天数";
        };

        System.out.println(dayName);
    }
}

switch语句提供了比多个if-else更清晰的多路分支选择方式。

powered by Gitbook© 2025 编外计划 | 最后修改: 2025-07-28 16:25:54

results matching ""

    No results matching ""