java switch與枚舉類型如何結(jié)合

小樊
81
2024-09-20 21:12:34

在Java中,你可以將switch語(yǔ)句與枚舉類型結(jié)合使用,以便根據(jù)枚舉值執(zhí)行不同的操作。以下是一個(gè)示例,展示了如何將switch語(yǔ)句與枚舉類型結(jié)合使用:

首先,定義一個(gè)枚舉類型:

public enum DayOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

接下來(lái),創(chuàng)建一個(gè)方法,該方法接受DayOfWeek枚舉值作為參數(shù),并使用switch語(yǔ)句根據(jù)枚舉值執(zhí)行不同的操作:

public class SwitchWithEnum {
    public static void main(String[] args) {
        DayOfWeek day = DayOfWeek.MONDAY;
        performActions(day);
    }

    public static void performActions(DayOfWeek day) {
        switch (day) {
            case MONDAY:
                System.out.println("Monday is the first day of the week.");
                break;
            case TUESDAY:
                System.out.println("Tuesday is the second day of the week.");
                break;
            case WEDNESDAY:
                System.out.println("Wednesday is the third day of the week.");
                break;
            case THURSDAY:
                System.out.println("Thursday is the fourth day of the week.");
                break;
            case FRIDAY:
                System.out.println("Friday is the fifth day of the week.");
                break;
            case SATURDAY:
                System.out.println("Saturday is the sixth day of the week.");
                break;
            case SUNDAY:
                System.out.println("Sunday is the seventh day of the week.");
                break;
            default:
                System.out.println("Invalid day.");
        }
    }
}

在這個(gè)示例中,performActions方法接受一個(gè)DayOfWeek枚舉值作為參數(shù)。然后,使用switch語(yǔ)句根據(jù)枚舉值執(zhí)行不同的操作。當(dāng)傳入的枚舉值為MONDAY時(shí),輸出"Monday is the first day of the week.“。當(dāng)傳入的枚舉值為SATURDAY時(shí),輸出"Saturday is the sixth day of the week.”。對(duì)于其他枚舉值,輸出"Invalid day."。

0