黑马程序员 java入门:switch语句

来源:互联网 发布:恒扬数据市值 编辑:程序博客网 时间:2024/06/07 05:28

---------------------- android培训java培训、期待与您交流! ------------------

switch语句

格式:

switch(表达式)

{

case 取值1:

执行语句;

break;

case 取值2:

执行语句;

break;

........

default:

执行语句;

break;


}


class SwitchDemo{public static void main(String[] args){int x=2;switch(x){case 4:System.out.println("a");case 6:System.out.println("b");case 2:System.out.println("c");default:System.out.println("d");//break; }System.out.println("Hello World!");}}

switch语句的特点:

1、switch语句选择的类型只有四种:byte,short,int,char

2、case之间与default没有顺序,先执行第一个case,没有匹配的case执行default

3、结束switch语句的两种情况:遇到break,执行到switch语句结束

4、如果匹配的case或者default没有对应的break,那么程序会继续向下执行,运行可以执行的语句,直到遇到break或者switch的结尾结束

class SwitchDemo{public static void main(String[] args){int x=2;switch(x)  //byte short int char{case 4:System.out.println("a");break;case 6:System.out.println("b");break;case 2:System.out.println("c");break;default:System.out.println("d");//break;}/*char类型的switch语句int  a=4,b=2;char ch=‘+’;switch(ch){case'-':System.out.println(a-b);break;case'+':System.out.println(a+b);break;case'*':System.out.println(a*b);break;case'\':System.out.println(a/b);break;default:System.out.println("feifa");}*/System.out.println("Hello World!");}}


class SwitchTest{public static void main(String[] args){//需求:根据用于指定月份,打印月份所属的季节int x=4;switch(x){case 3:case 4:case 5:System.out.println("春季");break;case 6:case 7:case 8:System.out.println("夏季");break;case 9:case 10:case 11:System.out.println("秋季");break;case 12:case 1:case 2:System.out.println("冬季");break;default:System.out.println("nono");}System.out.println("Hello World!");}}


if和switch语句很像

具体什么场景下,应用哪个语句

如果判断的具体数值不多,而是符合byte short int char这四种类型

虽然两个语句都可以使用,建议使用switch语句,因为效率稍高


其他情况:对于区间判断,对结果为boolean类型判断,使用if,if的使用范围更广





原创粉丝点击