现在来说明一个关于控制语句中switch容易容错的一个地方
例子如下:
- public class testSwitch{
- public static void main(String[] args){
- int x=2;
- switch(x){ //这个时候的表达式为整型
- case 1: //值也是整型
- System.out.println("hello,one");
- case 2:
- System.out.println("hello,two");
- case 3:
- System.out.println("hello,three");
- default:
- System.out.println("hello,every one");
- }
- }
- }
当表达式和值为整型和整数时输出结果为:hello,two
- public class testSwitch{
- public static void main(String[] args){
- char c='2';
- switch(c){ //这个时候的表达式为字符型
- case '1': //值也是字符型
- System.out.println("hello,one");
- case '2':
- System.out.println("hello,two");
- case '3':
- System.out.println("hello,three");
- default:
- System.out.println("hello,every one");
- }
- }
- }
当表达式和值为字符型和字符时的输出结果为:hello,two
- public class testSwitch{
- public static void main(String[] args){
- double x=2.0;
- switch(x){ //这个时候的表达式为double型会出现编译错误,为什么?
- case 1.0: //值也是double型
- System.out.println("hello,one");
- case 2.0:
- System.out.println("hello,two");
- case 3.0:
- System.out.println("hello,three");
- default:
- System.out.println("hello,every one");
- }
- }
- }
当表达式和值为doule型和doule数值的时候会出现编译错误.为什么会出现这个错误?大家可以想想,double和float都属于浮点类型,他们能表示精确的数值,会有失精度的可能,而且java中规定switch中的表达式类型只能是int型或char类型的.当我们对此并没有很清楚的话,经常可能就会犯这样的错误,而且这种题目经常在面试中出现,希望新手能够引起高度重视.