新手小记02

来源:互联网 发布:安装淘宝客户端 编辑:程序博客网 时间:2024/05/13 01:36

现在来说明一个关于控制语句中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类型的.当我们对此并没有很清楚的话,经常可能就会犯这样的错误,而且这种题目经常在面试中出现,希望新手能够引起高度重视.