您好,登錄后才能下訂單哦!
在case語句中不要使用枚舉類型來引用,直接使用枚舉類型的常量名稱即可。
在閱讀Java書籍和官方文檔的時候,都說Java的Switch語句是支持枚舉的,但是在網上找相關實例的時候卻沒有找到。通過查看官方文檔,明白了使用方法。
枚舉是一種static final的常量,但是在switch使用時和平時引用靜態常量有區別。因為switch條件中的枚舉類型必須和case語句里面的一致,所以當在switch語句中聲明了枚舉類型之后,case語句就已經確定了枚舉類型,所以不需要在使用枚舉類來引用了。
public?enum?Day?{ ????SUNDAY,?MONDAY,?TUESDAY,?WEDNESDAY, ????THURSDAY,?FRIDAY,?SATURDAY? }
?public?class?EnumTest?{ ????Day?day;???? ????public?EnumTest(Day?day)?{????????this.day?=?day; ????}???? ????public?void?tellItLikeItIs()?{????????switch?(day)?{????????????case?MONDAY://switch條件語句已經確定了枚舉類型,不需要再使用枚舉類型來引用枚舉常量,否則編譯出錯 ????????????????System.out.println("Mondays?are?bad.");????????????????break;???????????????????? ????????????case?FRIDAY: ????????????????System.out.println("Fridays?are?better.");????????????????break;????????????????????????? ????????????case?SATURDAY:?case?SUNDAY: ????????????????System.out.println("Weekends?are?best.");????????????????break;???????????????????????? ????????????default: ????????????????System.out.println("Midweek?days?are?so-so.");????????????????break; ????????} ????}???? ????public?static?void?main(String[]?args)?{ ????????EnumTest?firstDay?=?new?EnumTest(Day.MONDAY); ????????firstDay.tellItLikeItIs(); ????????EnumTest?thirdDay?=?new?EnumTest(Day.WEDNESDAY); ????????thirdDay.tellItLikeItIs(); ????????EnumTest?fifthDay?=?new?EnumTest(Day.FRIDAY); ????????fifthDay.tellItLikeItIs(); ????????EnumTest?sixthDay?=?new?EnumTest(Day.SATURDAY); ????????sixthDay.tellItLikeItIs(); ????????EnumTest?seventhDay?=?new?EnumTest(Day.SUNDAY); ????????seventhDay.tellItLikeItIs(); ????} }
? ? ? ? ?
? ? ? ? ? ? ? ? ? ?
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。