在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
值执行不同的逻辑。当day
为MONDAY
时,输出Today is Monday
;当day
为TUESDAY
时,输出Today is Tuesday
;以此类推。
通过这种方式,我们可以方便地根据枚举类型的不同值执行不同的逻辑,使代码更加清晰易懂。