在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."。