輸入年份及月份后獲取當月天數


思路

通過在一個數組中確定每個月份的天數,通過鍵盤獲取到年份及月份,先判斷輸入是否合法,輸入非法的話輸出提示,然后判斷是否為閏年,如果輸入的年份是閏年,則該月的2月份有29天,否則進入數組取得該月份對應的值作為天數返回並輸出。

代碼

import java.util.Scanner;

public class getDate {
    //定義一個月份天數數組
    static int[] arr = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    public static void main(String[] args) {
        Scanner scan =new Scanner(System.in);
        System.out.println("輸入年份及月份獲取該月天數,年份及月份用空格隔開:");
        int year = scan.nextInt();
        int month = scan.nextInt();
        int i;
        if(check_vaild(year,month)==-1){
            System.out.println("輸入錯誤");
        }else{
            System.out.println(check_vaild(year,month));
        }
    }

    public static int check_vaild(int year, int month) {
        if (month == 0 || month > 12) {
            return -1;
        }
        if (month != 2) {
            return arr[month];   //返回數組中每個月的天數
        } else {  //判斷閏年
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
                return 29;
            } else {
                return 28;
            }
        }
    }
}


免責聲明!

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



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