zoukankan      html  css  js  c++  java
  • 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”

  • 相关阅读:
    容器字段FieldContainer
    时间选择框
    Java 异常处理的优劣
    RSA 公钥加密算法
    Java 添加播放MIDI音乐
    Java 内存查看与分析
    总结 Eclipse 编程常用的快捷键
    Java 基础【03】序列化和反序列化
    找出给定字符串中出现最多的字符和次数
    Javascript 限制文本字节数
  • 原文地址:https://www.cnblogs.com/panpanpan/p/5983048.html
Copyright © 2011-2022 走看看