分別用switch語句和if語句實現鍵盤錄入月份,輸出對應的季節


  • 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 + "月是冬季");
        }
            
    }
}

結果:

 


免責聲明!

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



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