A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

class Demo {
       public static void main(String[] args) {
               int x = 3,y = 4 ;
               switch(x) {
                     case 0:
                        y++;  
                    default:
                        y++;
                   case 1:
                        y++;
                   case 2:
                        y++
                  System.out.println(y);
}
}
}

15 个回复

正序浏览
不动就问是好习惯,我喜欢自己研究,浪费大把时间,哎...
回复 使用道具 举报
赞一个,好问题
回复 使用道具 举报
不是很正常吗?
回复 使用道具 举报
兵蜂 发表于 2016-4-9 22:49
default 与case的优先级; case 穿透

好的,谢谢了
回复 使用道具 举报
慢慢分析 就知道了  
回复 使用道具 举报
zq19931995 来自手机 中级黑马 2016-4-9 23:10:05
11#
简单的穿透问题 楼上都给回复了 我就默默顶下吧
回复 使用道具 举报
因为case穿透了啊
回复 使用道具 举报
default 与case的优先级; case 穿透
回复 使用道具 举报
15614014298 发表于 2016-4-8 21:38
第一步执行default:y++,y=5
第二步执行到case1:y++,y=6
第三步执行到case2:y++,y=7

恩恩.明白了,谢谢哈
回复 使用道具 举报
李亚东_JAVAEE 发表于 2016-4-8 22:24
//本题考查case穿透现象
class Demo {
       public static void main(String[] args) {

恩恩,受教了
回复 使用道具 举报
Petergee 发表于 2016-4-8 22:35
class Demo {
       public static void main(String[] args) {
               int x = 3,y = 4 ;

哦.原来这个样的啊.明白了.我之前大意没有想到break
回复 使用道具 举报
我觉也是7
回复 使用道具 举报

class Demo {
       public static void main(String[] args) {
               int x = 3,y = 4 ;
               switch(x) {
                     case 0:
                        y++;  
                    default:
                        y++;
                   case 1:
                        y++;
                   case 2:
                        y++
                  System.out.println(y);
}
}
}
针对以上代码,由于case后面没有设置break,无法跳出,则会先跳转至dafault,
然后依次向下执行,至程序结束为止。
首先执行dafault,y++,y=5;
继续执行case1,y++,y=6;
继续执行case2,y++,y=7,
程序结束,输出y=7.
回复 使用道具 举报
//本题考查case穿透现象
class Demo {
       public static void main(String[] args) {
               int x = 3,y = 4 ;
               switch(x) {
                     case 0:   //x=0显然不符合,这种情况跳过,不执行
                        y++;  
                    default:  //x!=0,1,2,所以执行default,
                        y++;  //y=5
                   case 1:    //因为上面没有break;故发生case穿透现象,向下继续执行!
                        y++;  //y=6
                   case 2:
                        y++   //y=7
                  System.out.println(y);
}
}
}
回复 使用道具 举报
第一步执行default:y++,y=5
第二步执行到case1:y++,y=6
第三步执行到case2:y++,y=7
然后switch执行完毕,打印的y的值就是7
注,因为你执行的每个case并没有让switch结束,所以switch会一直执行下去
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马