在枚舉中使用switch-case語句時,可以根據枚舉常量的不同取值來執行不同的邏輯代碼。以下是一個示例:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
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");
}
在上面的示例中,我們聲明了一個枚舉類型Day
,并將day
賦值為Day.MONDAY
。然后使用switch-case語句根據day
的取值來輸出不同的信息。如果day
的取值不在枚舉常量中,則會執行default語句塊。