Java

如何在Java Switch中使用枚举

小樊
269
2024-06-28 11:57:29
栏目: 编程语言

在Java中,可以使用枚举类型作为Switch语句的条件。以下是一个示例:

public class EnumSwitchExample {

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

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

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

在这个示例中,我们定义了一个Day枚举类型,并在Switch语句中使用它来判断当前是星期几。通过将枚举类型作为Switch语句的条件,可以使代码更加清晰和易读,同时避免了使用多个if-else语句。

0
看了该问题的人还看了