1. 程式人生 > >廖雪峰Java1-3流程控制-4switch多重選擇

廖雪峰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語句