首页 > 其他 > 详细

switch 中可以使用字符串当判断条件

时间:2016-10-21 01:17:56      阅读:246      评论:0      收藏:0      [点我收藏+]

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”

switch 中可以使用字符串当判断条件

原文:http://www.cnblogs.com/panpanpan/p/5983048.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!