温馨提示×

如何在switch中使用枚举类型

小樊
99
2024-09-03 13:57:34
栏目: 编程语言

在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!”。

0