在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語句即可。