溫馨提示×

switchcase在枚舉中怎樣使用

小樊
242
2024-07-03 14:11:15
欄目: 編程語言

在枚舉中使用switch-case語句時,可以根據(jù)枚舉常量的不同取值來執(zhí)行不同的邏輯代碼。以下是一個示例:

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語句根據(jù)day的取值來輸出不同的信息。如果day的取值不在枚舉常量中,則會執(zhí)行default語句塊。

0