有趣的switch-case穿透

什么是case穿透

平时我们写 switch语句时,会搭配case,break,我们有时候会忘记写break,示例:

int choice = 1;
switch (choice) {
            case 1:        
                System.out.println("春天");
            case 2:
                System.out.println("夏天");
                break;
            default:
                System.out.println("hahaha");
        }

结果是什么呢?让我们输出一下

春天
夏天

这就是case穿透(去掉break),会自动进行下面的第二个case,直到遇到break

下面我们来试一试利用case穿透来判断季节

  int month= 1;
        switch (month) {
            case 1:
            case 2:
            case 3:
                System.out.println("春天");
                break;
            case 4:
            case 5:
            case 6:
                System.out.println("夏天");
                break;
            default:
                System.out.println("hahaha");

        }

完全没有问题,哈哈~~~~

猜你喜欢

转载自blog.csdn.net/qq_42224683/article/details/107247097
今日推荐