運算符和表達式 、 分支結構 輸入年份和月份,輸出該月的天數(使用switch-case)


思路:三個板塊,A.二月比較特殊,平年的二月只有28天,而閏年的二月有 29 天;

        B.4、6、9、11月;

        C.其他1、3、5、7、8、10、12月。

 

import java.util.Scanner;
public class DayOfMonth {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入年份(例如:2012)");
        int year = scanner.nextInt();
        System.out.println("請輸入月份(例如:1)");
        int month = scanner.nextInt();
        scanner.close();
        // 某月的天數
        int days = 0;
        switch (month) {
        case 2:
            // 判斷是否為閏年,閏年29天,非閏年28天
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                days = 29;
            } else {
                days = 28;
            }
            break;
        // 4,6,9,11為小月
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;
        // 其余為大月
        default:
            days = 31;
        }
        System.out.println(year + "年" + month + "月有" + days + "天");
    }
}

 


免責聲明!

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



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