switch 語(yǔ)句由一個(gè)控制表達(dá)式和多個(gè)case標(biāo)簽組成。
switch 控制表達(dá)式支持的類型有byte、short、char、int、enum(java 5)、String(Java 7)。
switch-case語(yǔ)句完全可以與if-else語(yǔ)句互轉(zhuǎn),但通常來(lái)說(shuō),switch-case語(yǔ)句執(zhí)行效率要高。
default在當(dāng)前switch找不到匹配的case時(shí)執(zhí)行。default并不是必須的。
一旦case匹配,就會(huì)順序執(zhí)行后面的程序代碼,而不管后面的case是否匹配,直到遇見break。
| 1234567891011 | switch (表達(dá)式) {case 條件1: 語(yǔ)句1; break;case 條件2: 語(yǔ)句2; break;...default: 語(yǔ)句;} |
| 1234567891011121314 | int i = 3;switch (i) {case 1: System.out.PRintln(1); break;case 2: System.out.println(2); break;case 3: System.out.println(3); break;default: System.out.println(0);} |
| 12345678910111213141516171819202122232425262728 | package net.xsoftlab.baike; public class TestSwitch { static enum E { A, B, C, D } public static void main(String args[]) { E e = E.B; switch (e) { case A: System.out.println("A"); break; case B: System.out.println("B"); break; case C: System.out.println("C"); break; case D: System.out.println("D"); break; default: System.out.println(0); } }} |
| 1234567891011121314 | String str = "C";switch (str) {case "A": System.out.println("A"); break;case "B": System.out.println("B"); break;case "C": System.out.println("C"); break;default: System.out.println(0);} |
break在switch中用于結(jié)束當(dāng)前流程。
一旦case匹配,就會(huì)順序執(zhí)行后面的程序代碼,而不管后面的case是否匹配,直到遇見break。
示例:
| 1234567891011 | int i = 2;switch (i) {case 1: System.out.println(1);case 2: System.out.println(2);case 3: System.out.println(3);default: System.out.println(0);} |
輸出結(jié)果:
| 123 | 230 |
實(shí)例:輸出2015年指定月份的最大天數(shù)
| 12345678910111213141516171819202122232425 | int year = 2015;int month = 8;int day = 0;switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12: day = 31; break;case 2: day = 28; break;case 4:case 6:case 9:case 11: day = 30; break;} System.out.println(day); |
default在當(dāng)前switch找不到匹配的case時(shí)執(zhí)行。default并不是必須的。
示例:
| 123456789 | int x = 0;switch (x) {case 1: System.out.println(1);case 2: System.out.println(2);default: System.out.println("default");} |
輸出結(jié)果:
| 1 | default |
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注