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