当前位置: 代码迷 >> 综合 >> switch-case中接受的参数类型
  详细解决方案

switch-case中接受的参数类型

热度:66   发布时间:2023-10-27 16:39:43.0

Switch-case中接受的参数类型

 

switch(参数){

     case  常量表达式1break;

     case  常量表达式1break;

     …

     Default:break;

}

 

switch接受的参数类型有10种,分别是基本类型的byte,short,int,char,以及引用类型的String(只有JavaSE 7 和以后的版本可以接受String类型参数),enumbyte,short,int,char的封装类Byte,Short,Integer,Character

case后紧跟常量表达式,不能是变量。

default语句可有可无,如果没有case语句匹配,default语句会被执行。

case语句和default语句后的代码可不加花括号。

如果某个case语句匹配,那么case后面的语句块会被执行,并且如果后面没有break关键字,会继续执行后面的case语句代码和default,直到遇见break或者右花括号。

default后无需跟常量表达式。

 String msg = "Tim";  


 switch(msg) {  

 case "kate": System.out.println("rabbit ");  

 case "Tim": System.out.println("Tim,happy new year");  

default:System.out.println("what ?");  

 case "Lucy": System.out.println("monkey");

break;  

case "Jean" : System.out.println("dokudoku!!");  

 输出结果:

 happy new year  

 what ?  

monkey  

上面例子说明了两个问题,第一个是不加break的后果,第二个是default的位置影响。

public static void main(String[] args) {
  
        switch (new Integer(45)) {
  
        case 40:
            System.out.println("40");
            break;
        case 45:
            System.out.println("45");//将会打印这句
            break;
        default:
            System.out.println("?");
            break;
        }
    }

  相关解决方案