在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
;以此類推。
通過這種方式,我們可以方便地根據枚舉類型的不同值執行不同的邏輯,使代碼更加清晰易懂。