如何在switch中使用枚举类型

avatar
作者
筋斗云
阅读量:0

在Java和C#等编程语言中,可以在switch语句中使用枚举类型

  1. 首先,定义一个枚举类型。例如,这里定义了一个表示一周中各天的枚举类型:
public enum Day {     MONDAY,     TUESDAY,     WEDNESDAY,     THURSDAY,     FRIDAY,     SATURDAY,     SUNDAY } 
  1. 然后,在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语句来判断它的值,并输出相应的信息。当dayFRIDAY时,输出“Friday, weekend is here!”。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!