国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Java switch 詳解

2019-11-14 09:04:16
字體:
供稿:網(wǎng)友

switch 語句由一個控制表達式和多個case標(biāo)簽組成。

switch 控制表達式支持的類型有byte、short、char、int、enum(java 5)、String(Java 7)。

switch-case語句完全可以與if-else語句互轉(zhuǎn),但通常來說,switch-case語句執(zhí)行效率要高。

default在當(dāng)前switch找不到匹配的case時執(zhí)行。default并不是必須的。

一旦case匹配,就會順序執(zhí)行后面的程序代碼,而不管后面的case是否匹配,直到遇見break。

| |目錄

1語法格式2使用示例·int類型switch示例·枚舉(Enum)類型switch示例·String類型switch示例3break·忘記寫break的陷阱·巧用break4default

1語法格式

1234567891011switch (表達式) {case 條件1:    語句1;    break;case 條件2:    語句2;    break;...default:    語句;}

2使用示例

int類型switch示例

1234567891011121314int 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);}

枚舉(Enum)類型switch示例

12345678910111213141516171819202122232425262728package 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);        }    }}

String類型switch示例

1234567891011121314String 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);}

3break

break在switch中用于結(jié)束當(dāng)前流程。

一旦case匹配,就會順序執(zhí)行后面的程序代碼,而不管后面的case是否匹配,直到遇見break。

忘記寫break的陷阱

示例:

1234567891011int 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é)果:

123230

巧用break

實例:輸出2015年指定月份的最大天數(shù)

12345678910111213141516171819202122232425int 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);

4default

default在當(dāng)前switch找不到匹配的case時執(zhí)行。default并不是必須的。

示例:

123456789int x = 0;switch (x) {case 1:    System.out.println(1);case 2:    System.out.println(2);default:    System.out.println("default");}

輸出結(jié)果:

1default

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 广宁县| 谢通门县| 东莞市| 福海县| 隆子县| 嘉荫县| 开鲁县| 临沂市| 铁岭县| 大新县| 西畴县| 鲜城| 长泰县| 百色市| 临猗县| 渑池县| 永春县| 安阳市| 樟树市| 津南区| 易门县| 南漳县| 泾源县| 东莞市| 西吉县| 常州市| 蒲城县| 吉首市| 涿鹿县| 泌阳县| 榆林市| 温泉县| 永济市| 柘荣县| 开原市| 紫阳县| 常山县| 额敏县| 嘉荫县| 安化县| 怀远县|