阅读量:0
在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!”。