温馨提示×

java中enum怎样与switch配合使用

小樊
121
2024-07-15 11:53:36
栏目: 编程语言

在Java中,可以使用enum与switch语句配合使用来实现根据枚举类型的不同值执行不同的逻辑。以下是一个示例代码:

public class EnumSwitchExample {
    
    public 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("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");
                break;
        }
    }
}

在上面的例子中,我们定义了一个枚举类型Day表示一周的每一天,然后在main方法中使用switch语句根据不同的Day值执行不同的逻辑。当dayMONDAY时,输出Today is Monday;当dayTUESDAY时,输出Today is Tuesday;以此类推。

通过这种方式,我们可以方便地根据枚举类型的不同值执行不同的逻辑,使代码更加清晰易懂。

0