在Java中,可以使用枚举(Enum)来优化switch语句,使代码更加简洁、易读和易于维护
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
printDayMessage
的方法,它接受一个Day
类型的参数,并根据参数值输出相应的信息:public static void printDayMessage(Day day) {
switch (day) {
case MONDAY:
System.out.println("星期一,开始新的工作周!");
break;
case TUESDAY:
System.out.println("星期二,继续努力工作!");
break;
case WEDNESDAY:
System.out.println("星期三,保持工作热情!");
break;
case THURSDAY:
System.out.println("星期四,快到下班时间了!");
break;
case FRIDAY:
System.out.println("星期五,下班啦!");
break;
case SATURDAY:
System.out.println("星期六,享受周末!");
break;
case SUNDAY:
System.out.println("星期日,好好休息!");
break;
default:
System.out.println("无效的星期!");
}
}
printDayMessage
方法,传入不同的枚举值,测试输出结果:public static void main(String[] args) {
printDayMessage(Day.MONDAY);
printDayMessage(Day.TUESDAY);
printDayMessage(Day.WEDNESDAY);
printDayMessage(Day.THURSDAY);
printDayMessage(Day.FRIDAY);
printDayMessage(Day.SATURDAY);
printDayMessage(Day.SUNDAY);
}
通过使用枚举类型和switch语句,我们可以实现更简洁、易读和易于维护的代码。当需要添加或删除某个天数时,只需修改枚举类型和相应的case语句即可。