Java输出某年某年月的天数

Java输出某年某年月的天数_第1张图片

小伙伴,你觉的那种方式更优雅啊,如果你有更好的解法,告知sam_liu,谢谢了哦!

第一种实现方式

package month;

import java.util.Scanner;

public class Date {
    public static void main(String[] args) {

        System.out.println("请输入年份:");
        Scanner inYear = new Scanner(System.in);
        int year = inYear.nextInt();

        System.out.println("请输入月份:");
        Scanner inMonth = new Scanner(System.in);
        int month = inMonth.nextInt();

        int numDays = 0;
        switch(month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)) {
                    numDays = 29;
                }else {
                    numDays = 28;
                }
                break;
        }
        System.out.println(year + "年" + month + "月份" + "有" + numDays + "天");
    }
}

运行结果

Java输出某年某年月的天数_第2张图片

第二种实现方式

package month;

import java.util.Scanner;

public class GetDade {
    public static void main(String[] args) {
        GetDade date = new GetDade();
        int monthList[]  = new int[12];
        int numDays = 0;
        for(int i = 0; i < monthList.length; i++) {
            monthList[i] = i+1;
        }

        System.out.println("请输入年份");
        Scanner inYear = new Scanner(System.in);
        int year = inYear.nextInt();
        System.out.println("请输入月份");
        Scanner inMonth = new Scanner(System.in);
        int month = inMonth.nextInt();

        if((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)) {
            if(month == 2) {
                numDays = 29;
            }else {
                numDays = 28;
            }
        }else{
            for(int j = 0; j < 12; j++) {
                if(!(monthList[j] % 2 == 0) || (month == 1)) {
                    numDays = 31;
                }else if (monthList[j] % 2 == 0) {
                    numDays = 30;
                }
            }
        }

        System.out.println(year + "年" + month + "月份" + "有" + numDays + "天");



    }
}

运行结果

Java输出某年某年月的天数_第3张图片

你可能感兴趣的:(笔记)