如何在Java Switch中使用枚举

avatar
作者
筋斗云
阅读量:0

在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语句。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!