switchcase

switchcase在枚举中怎样使用

小樊
268
2024-07-03 14:11:15
栏目: 编程语言

在枚举中使用switch-case语句时,可以根据枚举常量的不同取值来执行不同的逻辑代码。以下是一个示例:

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

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,并将day赋值为Day.MONDAY。然后使用switch-case语句根据day的取值来输出不同的信息。如果day的取值不在枚举常量中,则会执行default语句块。

0
看了该问题的人还看了