java switch与枚举类型如何结合

avatar
作者
猴君
阅读量:0

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!