在Java和C#等編程語言中,可以在switch
語句中使用枚舉類型
public enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
switch
語句中使用該枚舉類型的變量。例如,以下代碼根據輸入的星期幾來輸出相應的信息:public class SwitchEnumExample {
public static void main(String[] args) {
Day day = Day.FRIDAY;
switch (day) {
case MONDAY:
System.out.println("Monday, start of the week.");
break;
case TUESDAY:
System.out.println("Tuesday, keep going.");
break;
case WEDNESDAY:
System.out.println("Wednesday, halfway there.");
break;
case THURSDAY:
System.out.println("Thursday, almost weekend.");
break;
case FRIDAY:
System.out.println("Friday, weekend is here!");
break;
case SATURDAY:
System.out.println("Saturday, enjoy the weekend!");
break;
case SUNDAY:
System.out.println("Sunday, relax and recharge.");
break;
default:
System.out.println("Invalid day.");
break;
}
}
}
在這個例子中,我們將Day
枚舉類型的變量day
設置為FRIDAY
,然后使用switch
語句來判斷它的值,并輸出相應的信息。當day
為FRIDAY
時,輸出“Friday, weekend is here!”。