- switch建議判斷固定值的時候用
- if建議判斷區間或范圍的時候用
1.用switch實現鍵盤錄入月份,輸出對應的季節
import java.util.Scanner; class Hello2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("請輸入月份"); int month = sc.nextInt(); switch (month) { case 3: case 4: case 5: System.out.println(month + "月是春季"); break; case 6: case 7: case 8: System.out.println(month + "月是夏季"); break; case 9: case 10: case 11: System.out.println(month + "月是秋季"); break; case 12: case 1: case 2: System.out.println(month + "月是冬季"); break; default: System.out.println("沒有對應的季節"); break; } } }
結果:
2.用if實現鍵盤錄入月份,輸出對應的季節
import java.util.Scanner; class Hello2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("請輸入月份"); int month = sc.nextInt(); if (month > 12 && month < 1) { System.out.println("沒有對應的季節"); }else if (month >= 3 && month <=5) { System.out.println(month + "月是春季"); }else if (month >=6 && month <=9) { System.out.println(month + "月是夏季"); }else if (month >=10 && month <=12) { System.out.println(month + "月是秋季"); }else if (month >=1 && month <= 3) { System.out.println(month + "月是冬季"); } } }
結果: