Java實戰--判斷年份為閏年還是平年


判斷閏年平年,並輸出某月天數

題目

給定一個年份,判斷是閏年還是平年,再給定一個月份,輸出該月的天數。

分析

閏年的判斷條件是:

  1. 能被4整除但不被100整除
  2. 能被400整除

代碼

package practice;

import java.util.Scanner;
public class LeapYear {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入年份:");
        int year = scanner.nextInt();
        if(isLeapYear(year)){
            System.out.println("該年為閏年");
        }else{
            System.out.println("該年為平年");
        }
        System.out.println("請輸入月份:");
        int month = scanner.nextInt();
        int days;
        while(month>12||month<1){
            System.out.println("月份輸入有誤,請重新輸入");
        }
        switch (month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:{
                days = 31;
                break;
            }
            case 4:
            case 6:
            case 9:
            case 11:{
                days = 30;
                break;
            }
            default:{
                if(isLeapYear(year)){
                    days = 29;
                }else{
                    days = 28;
                }
            }
        }
        System.out.println("該月有"+days+"天");
    }

    public static boolean isLeapYear(int y){
        if(y%4==0&&y%100!=0||y%400==0){
            return true;
        }else{
            return false;
        }
    }
}

輸出結果

image-20210823155957586


免責聲明!

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



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