输入年份及月份后获取当月天数

思路

通过在一个数组中确定每个月份的天数,通过键盘获取到年份及月份,先判断输入是否合法,输入非法的话输出提示,然后判断是否为闰年,如果输入的年份是闰年,则该月的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;
            }
        }
    }
}

posted @ 2021-03-04 16:31  B1nbin  阅读(1139)  评论(0编辑  收藏  举报
/*
*/