首页 技术 正文
技术 2022年11月16日
0 收藏 486 点赞 2,733 浏览 952 个字

switch语句和if-else语句不同,switch语句可以有多个可能的执行路径。在第四版java编程思想介绍switch语句的语法格式时写到:

switch (integral-selector) {
case integral-value1:
statement;
break;
case integral-value12:
statement;
break;
default:
statement;
}

其中integral-selector(整数选择因子)是一个能产生整数值的表达式。并且说明选择因子必须是一个int或者char那样的整数值,或者是一个enum枚举类型。由于java编程思想第四版是在JDK1.5的基础上进行编写的,所以对现在来说当时的书中介绍的难免有过时之处。

java官方手册中找到switch语句的说明中,已经明确指出了 A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types , the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer。其中enum枚举类型是JDK1.5中新增加的新特性,而switch对于String字符串的支持则是在JDK7以后。

在使用JDK7版本的环境进行编程时,使用switch语句的选择因子,如果不符合规范(比如float类型变量)会产生提示: Cannot switch on a value of type float. Only convertible int values, strings or enum variables are permitted 由于, byte,short,char 都可以隐含转换为 int 所以int类型变量中也包含了byte,short,char类型变量。

总结:

可以用作switch选择因子的数据类型有:

  • char,byte,short,int以及他们的包装类Character,Byte,Short,Integer
  • enmu枚举 (since jdk1.5)
  • String字符串(since jdk1.7)
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,580
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918