switch語句能否作用在byte上,能否作用在long上,能否作用在String上?
在switch(expr1)中,expr1只能是一個整數表達式或者枚舉常量(更大字體),整數表達式可以是int基本類型或Integer包裝類型,由於,byte,short,char都可以隱含轉換為int,所以,這些類型以及這些類型的包裝類型也是可以的。顯然,long和String類型都不符合switch的語法規定(版本原因),並且不能被隱式轉換成int類型,所以,它們不能作用於swtich語句中。
Java7之前,switch只能支持 byte、short、char、int或者其對應的封裝類以及Enum類型。在Java7中已經支持String類型。
//枚舉類型,把要判斷的條件先定義成enum
enum CompassPoint {
case North
case South
case East
case West
}
//使用 Switch 語句來匹配枚舉值
directionToHead = .South
switch directionToHead {
case .North:
println("Lots of planets have a north")
case .South:
println("Watch out for penguins")
case .East:
println("Where the sun rises")
case .West:
println("Where the skies are blue")
}
// 輸出"Watch out for penguins”
