在Java中,你可以將switch
語句與枚舉類型結合使用,以便根據枚舉值執行不同的操作。以下是一個示例,展示了如何將switch
語句與枚舉類型結合使用:
首先,定義一個枚舉類型:
public enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
接下來,創建一個方法,該方法接受DayOfWeek
枚舉值作為參數,并使用switch
語句根據枚舉值執行不同的操作:
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.");
}
}
}
在這個示例中,performActions
方法接受一個DayOfWeek
枚舉值作為參數。然后,使用switch
語句根據枚舉值執行不同的操作。當傳入的枚舉值為MONDAY
時,輸出"Monday is the first day of the week.“。當傳入的枚舉值為SATURDAY
時,輸出"Saturday is the sixth day of the week.”。對于其他枚舉值,輸出"Invalid day."。