switch 中可以使用字符串當判斷條件


switch語句能否作用在byte上,能否作用在long上,能否作用在String?

   在switchexpr1)中,expr1只能是一個整數表達式或者枚舉常量(更大字體),整數表達式可以是int基本類型或Integer包裝類型,由於,byte,short,char都可以隱含轉換為int,所以,這些類型以及這些類型的包裝類型也是可以的。顯然,longString類型都不符合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”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM