温馨提示×

Java枚举的switch语句编写方法是什么

小樊
84
2024-08-09 09:34:40
栏目: 编程语言

在Java中,可以使用switch语句处理枚举类型。下面是一个示例代码,展示了如何使用switch语句处理枚举类型:

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

public class Main {
    public static void main(String[] args) {
        Day day = Day.MONDAY;

        switch(day) {
            case MONDAY:
                System.out.println("Today is Monday");
                break;
            case TUESDAY:
                System.out.println("Today is Tuesday");
                break;
            case WEDNESDAY:
                System.out.println("Today is Wednesday");
                break;
            case THURSDAY:
                System.out.println("Today is Thursday");
                break;
            case FRIDAY:
                System.out.println("Today is Friday");
                break;
            case SATURDAY:
                System.out.println("Today is Saturday");
                break;
            case SUNDAY:
                System.out.println("Today is Sunday");
                break;
            default:
                System.out.println("Invalid day");
        }
    }
}

在上面的示例中,我们首先定义了一个枚举类型Day,然后在Main类中使用switch语句根据不同的枚举值执行不同的操作。在switch语句中,我们列出了枚举类型Day的所有可能取值,并针对每个值编写了相应的处理逻辑。如果枚举类型Day的取值不在case列表中,则执行default分支的操作。

0