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”

转载于:https://www.cnblogs.com/panpanpan/p/5983048.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值