Java枚举值能做为switch参数吗

avatar
作者
筋斗云
阅读量:0

是的,Java枚举值可以作为switch语句的参数。枚举类型是一种特殊的类,它表示一组固定的常量,可以将枚举值作为switch语句的参数,根据不同的枚举值执行不同的逻辑。以下是一个示例:

public class EnumExample {          public enum Weekday {         MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY     }          public static void main(String[] args) {         Weekday day = Weekday.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");         }     } } 

在上面的示例中,我们定义了一个Weekday枚举类型,然后使用switch语句根据不同的枚举值打印不同的消息。当day为Weekday.MONDAY时,输出为"Today is Monday"。

广告一刻

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