廖雪峰Java1-3流程控制-4switch多重选择

switch语句

根据switch(表达式)跳转到匹配的case结果,继续执行case结果: 的后续语句,遇到break结束执行,没有匹配条件,执行default语句。

        int i = 3
        switch (i){
            case 1:
                System.out.println("武林盟主");
                break;
            case 2:
                System.out.println("少林方丈");
                break;
            case 3:
                System.out.println("华山掌门");
                break;
            default:
                System.out.println("峨眉掌门");
        }

  • switch语句相当于一组if else 语句,执行的总是相等的判断。
  • switch语句没有花括号,是以 ":" 开头的
  • case语句具有穿透性,如果没有break会继续执行
        //switch的穿透性
        Scanner s = new Scanner(System.in);
        System.out.print("请输入名次:");
        int option = s.nextInt();
        switch (option){
            case 1:
                System.out.println("武林盟主");
                break;
            case 2:
                System.out.println("少林方丈");
                break;
            case 3:
                System.out.println("华山掌门");
            default:
                System.out.println("峨眉掌门");
        }

  • 如果有几种情况需要执行相同的语句
public class Hello {
    public static void test(int option) {
        switch (option) {
            case 1:
                System.out.println("武林盟主");
                break;
            //case2和case3执行相同的操作
            case 2:
            case 3:
                System.out.println("华山掌门");
                break;
            default:
                System.out.println("峨眉掌门");
        }
    }
    public static void main(String[] args){
        test(2);
        test(3);
    }
}

除了整型,还可以使用字符串匹配,字符串比较内容相等

总结:

  • switch语句可以做多重选择
  • switch的计算结果必须是整型、字符串或枚举类型
  • 不要漏泄break,打开fall-through警告
  • 总是写上default,建议打开missing default警告
  • 尽量少用switch语句

猜你喜欢

转载自www.cnblogs.com/csj2018/p/10252505.html