y不应该等于4吗? CASE 4:也执行吗? switch(x) 和 case 4 不匹配吗 也执行!?public class ErWei222{public static void main(String[] args){int x = 2,y=3;switch(x){default:y++;case 3:y++;break;case 4:y++;}System.out.println("y="+y);}}
2 回答

杨__羊羊
TA贡献1943条经验 获得超7个赞
你执行下这段代码就知道了
public class ErWei222 { public static void main(String[] args) { int x = 2 , y = 3 ; switch (x) { default : y++; System.out.println( "default >> y=" + y); case 3 : y++; System.out.println( "case 3 >> y=" + y); break ; case 4 : y++; System.out.println( "case 4 >> y=" + y); } System.out.println( "y=" + y); } } |
最开始进入default,y++,y变成4
然后因为default没有break,所以会向下穿透,进入case 3 ,y++,y变成5
case 3有break,所以最后从这里跳出switch语句块
所以最终y=5

至尊宝的传说
TA贡献1789条经验 获得超10个赞
1:进入switch语句后,case 3和case 4都不匹配, 程序进入default语句
2:执行完default语句后y=4 ,由于defalut语句在最前面并且没有break跳出,那么继续执行case3
3: case3执行完后y=5, case 3 写了break.所以跳出
最后输出y=5
一般情况下.switch case 语句的伪代码如下
switch (参数) { case 值 1 : 语句 1 ; break ; case 值 2 : 语句 2 break ; .... default : 语句; break ; //default在最后面写,那么这个break可以省略 } |
添加回答
举报
0/150
提交
取消