选择语句-switch
switch语句格式
switch(表达式) {case 常量值1:语句体1;break;case 常量值2:语句体2;break;...default:语句体n;break;}
首先计算出表达式的值
其次,和case依次比较,一旦有对应的值,就会执行相应的语句,在执行的过程中,遇到break就会结束。
最后,如果所有的case都和表达式的值不匹配,就会执行default语句体部分,然后程序结束掉。
public class Test {public static void main(String[] args) {int day = 7;switch (day) {case 1:System.out.println("星期一");break;case 2:System.out.println("星期二");break;case 3:System.out.println("星期三");break;case 4:System.out.println("星期四");break;case 5:System.out.println("星期五");break;case 6:System.out.println("星期六");break;case 7:System.out.println("星期日");break;default:System.out.println("error");break;}}}
在switch语句中,如果case的后面不写break,将出现穿透现象,也就是不会在判断下一个case的值,直接向后运 行,直到遇到break,或者整体switch结束。
public class Test {public static void main(String[] args) {int day = 1;switch (day) {case 1:System.out.println("星期一");case 2:System.out.println("星期二");case 3:System.out.println("星期三");case 4:System.out.println("星期四");case 5:System.out.println("星期五");case 6:System.out.println("星期六");case 7:System.out.println("星期日");default:System.out.println("error");}}}
