標籤:style blog color 使用 re div
switch的特點:只接受byte,shotr,int,char
語句的定義順序可以隨意的,但執行順序還是從第一個case開始
public class SwitchDemo { public static void main(String[] args) { int x = 4; switch (x) { case 1: System.out.println("a"); break; case 2: System.out.println("b"); break; case 3: System.out.println("c"); break; case 4: System.out.println("d"); break;//遇到滿足條件的就執行該語句並跳出switch語句 default: System.out.println("e"); break;//可以省略不寫,遇到括弧就會結束 } }}
無論default放在什麼位置,運算都是從第一個case開始,所有case判斷完才執行default
所有case不符合,執行default,之後沒有break繼續執行下面的語句不再判斷case,只執行語句,直到遇到break或括弧結束switch語句
public class SwitchDemo { public static void main(String[] args) { int x = 4; switch(x) { default: System.out.println("e"); //break; case 1: System.out.println("a"); //break; case 2: System.out.println("b"); break; case 3: System.out.println("c"); break; } }}
什麼時候用if 什麼時候用switch
if和switch語句很像 具體什麼情境下 應用那個語句呢
如果具體數值不多而且符合byte short int char這四種類型
雖然兩個語句都可以使用,建議使用switch語句,因為效率稍高
其他情況:對區間判斷,對結果為boolean類型判斷使用if if的使用範圍更廣
流程式控制制語句_switch