標籤:運算式 color ring 條件 switch class out public 支援
switch 語句由一個控製表達式和多個case標籤組成。
switch 控製表達式支援的類型有byte、short、char、int、enum(Java 5)、String(Java 7)。
switch-case語句完全可以與if-else語句互轉,但通常來說,switch-case語句執行效率要高。
default在當前switch找不到匹配的case時執行。default並不是必須的。
一旦case匹配,就會順序執行後面的程式碼,而不管後面的case是否匹配,直到遇見break。
switch文法格式
switch (運算式) {case 條件1: 語句1; break;case 條件2: 語句2; break;...default: 語句;}
分支語句先對錶達式進行求值,然後依次匹配條件1,條件2... ...當運算式的值於條件相匹配時,執行對應的語句,如果沒有對應對條件,則執行default語句。
byte:
1 byte b1=12; 2 switch(b1){ 3 case 1: 4 System.out.println("wrong"); 5 break; 6 7 case 2: 8 System.out.println("wrong2"); 9 break;10 11 case 12:12 System.out.println("right");13 break;14 15 default:16 System.out.println("all wrong");17 }
int:
1 int num1=12; 2 switch(num1){ 3 case 1: 4 System.out.println("wrong"); 5 break; 6 7 case 2: 8 System.out.println("wrong2"); 9 break;10 11 case 12:12 System.out.println("right");13 break;14 15 default:16 System.out.println("all wrong");17 }
char:
1 char c1=‘a‘; 2 switch (c1) { 3 case ‘a‘: 4 System.out.println("a is right"); 5 break; 6 7 case ‘b‘: 8 System.out.println("b is right"); 9 break;10 11 case ‘c‘:12 System.out.println("c is right");13 break;14 default:15 break;16 }
string:
1 String str1="123"; 2 switch (str1) { 3 case "111": 4 System.out.println("111 is right"); 5 break; 6 7 case "112": 8 System.out.println("112 is right"); 9 break;10 11 case "123":12 System.out.println("123 is right");13 break;14 default:15 System.out.println(" no right");16 break;17 }
Enum:
1 static enum E{ 2 A,B,C,D 3 } 4 public static void main(String[] args) { 5 E e=E.C; 6 7 switch (e) { 8 case A: 9 System.out.println("A is right");10 break;11 12 case B:13 System.out.println("B is right");14 break;15 16 case C:17 System.out.println("C is right");18 break;19 20 case D:21 System.out.println("D is right");22 break; 23 default:24 System.out.println("no right");25 break;26 }
java基礎之switch