Java

Java中如何使用switch语句处理枚举类型

小樊
103
2024-08-09 09:30:37
栏目: 编程语言

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

public class EnumExample {
    
    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的值来判断今天是星期几并输出对应的信息。

0
看了该问题的人还看了