新手小记02

现在来说明一个关于控制语句中switch容易容错的一个地方

例子如下:

  1. public class testSwitch{
  2.  public static void main(String[] args){
  3.    int x=2;
  4.     switch(x){ //这个时候的表达式为整型
  5.       case 1: //值也是整型
  6.          System.out.println("hello,one");
  7.       case 2:
  8.          System.out.println("hello,two");
  9.       case 3:
  10.          System.out.println("hello,three");
  11.       default:
  12.          System.out.println("hello,every one");
  13.               }
  14.        }
  15. }

当表达式和值为整型和整数时输出结果为:hello,two

  1. public class testSwitch{
  2.  public static void main(String[] args){
  3.    char c='2';
  4.     switch(c){ //这个时候的表达式为字符型
  5.       case '1'//值也是字符型
  6.          System.out.println("hello,one");
  7.       case '2':
  8.          System.out.println("hello,two");
  9.       case '3':
  10.          System.out.println("hello,three");
  11.       default:
  12.          System.out.println("hello,every one");
  13.               }
  14.        }
  15. }

当表达式和值为字符型和字符时的输出结果为:hello,two

  1. public class testSwitch{
  2.  public static void main(String[] args){
  3.    double x=2.0;
  4.     switch(x){ //这个时候的表达式为double型会出现编译错误,为什么?
  5.       case 1.0//值也是double型
  6.          System.out.println("hello,one");
  7.       case 2.0:
  8.          System.out.println("hello,two");
  9.       case 3.0:
  10.          System.out.println("hello,three");
  11.       default:
  12.          System.out.println("hello,every one");
  13.               }
  14.        }
  15. }

 

当表达式和值为doule型和doule数值的时候会出现编译错误.为什么会出现这个错误?大家可以想想,double和float都属于浮点类型,他们能表示精确的数值,会有失精度的可能,而且java中规定switch中的表达式类型只能是int型或char类型的.当我们对此并没有很清楚的话,经常可能就会犯这样的错误,而且这种题目经常在面试中出现,希望新手能够引起高度重视.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值