標籤:with ted variable break character spec pes case jdk
switch語句和if-else語句不同,switch語句可以有多個可能的執行路徑。在第四版java編程思想介紹switch語句的文法格式時寫到:
switch (integral-selector) { case integral-value1: statement; break; case integral-value12: statement; break; default: statement; }
其中integral-selector(整數選擇因子)是一個能產生整數值的運算式。並且說明選擇因子必須是一個int或者char那樣的整數值,或者是一個enum枚舉類型。由於java編程思想第四版是在JDK1.5的基礎上進行編寫的,所以對現在來說當時的書中介紹的難免有過時之處。
在java官方手冊中找到switch語句的說明中,已經明確指出了 A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types , the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer。其中enum枚舉類型是JDK1.5中新增加的新特性,而switch對於String字串的支援則是在JDK7以後。
在使用JDK7版本的環境進行編程時,使用switch語句的選擇因子,如果不符合規範(比如float類型變數)會產生提示: Cannot switch on a value of type float. Only convertible int values, strings or enum variables are permitted 由於, byte,short,char 都可以隱含轉換為 int 所以int類型變數中也包含了byte,short,char類型變數。
總結:
可以用作switch選擇因子的資料類型有:
- char,byte,short,int以及他們的封裝類Character,Byte,Short,Integer
- enmu枚舉 (since jdk1.5)
- String字串(since jdk1.7)
JAVA編程思想(第四版)學習筆記----4.8 switch(知識點已更新)