Java中switch語句用法


語法:switch的字面值跟case的字面值相等,就執行case語句,如果所有的      case 跟switch的字面值不相等,執行 default語句。

switch(字面值){   case 字面值1:     輸出語句,變量。。。     break;   case 字面值2:     輸出語句,變量。。。     break;   case 字面值3:     輸出語句,變量。。。     break;   ...   default:     輸出語句,其他。。。 }

案例一:

public class java01 { public static void main(String[] args) { // 周一 寫代碼 // 周二 看電影 // 周三 打籃球 // 周四 約會 // 周五 爬山 // 其他 不在計划范圍
        int day = 3;  //表示周三
        switch (day){ case 1: System.out.println("寫代碼"); break; case 2: System.out.println("看電影"); break; case 3: System.out.println("打籃球"); break; case 4: System.out.println("約會"); break; case 5: System.out.println("爬山"); break; default: System.out.println("不在計划范圍。。。"); } } }
輸出結果:打籃球

 案例二:case穿透(忘記寫break)

如果switch語句都不寫break,從成立的那個case一直穿透到最后!

public class java02 { public static void main(String[] args) {
        int day = 3;    //表示周三
        switch (day){ case 1: System.out.println("寫代碼"); case 2: System.out.println("看電影"); case 3: System.out.println("打籃球"); case 4: System.out.println("約會"); case 5: System.out.println("爬山"); default: System.out.println("不在計划范圍。。。"); } } } 輸出結果:打籃球 約會 爬山 不在計划范圍。。。 

 案例三:case並列

public class java01 { public static void main(String[] args) { // 春天-----3月 4月 5月 // 夏天-----6月 7月 8月 // 秋天-----9月 10月 11月 // 冬天-----12月 1月 2月
        int month = 7; switch (month){ case 3: case 4: case 5: //month如果是3或者4或者5都執行春天!
                System.out.println("春天"); break; case 6: case 7: case 8: System.out.println("夏天"); break; case 9: case 10: case 11: System.out.println("秋天"); break; case 12: case 1: case 2: System.out.println("冬天"); break; default: System.out.println("沒有這個季節!"); } } }
運行結果:夏天

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM