Java

java万年历实现代码怎么写

小亿
85
2023-12-14 03:04:28
栏目: 编程语言

以下是一个简单的Java万年历实现代码:

import java.util.Scanner;

public class CalendarProgram {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入年份:");
        int year = scanner.nextInt();
        System.out.print("请输入月份:");
        int month = scanner.nextInt();

        printCalendar(year, month);

        scanner.close();
    }

    public static void printCalendar(int year, int month) {
        int daysInMonth = getDaysInMonth(year, month);
        int startDayOfWeek = getStartDayOfWeek(year, month);

        System.out.println("日\t一\t二\t三\t四\t五\t六");

        for (int i = 0; i < startDayOfWeek; i++) {
            System.out.print("\t");
        }

        for (int day = 1; day <= daysInMonth; day++) {
            System.out.print(day + "\t");

            if ((day + startDayOfWeek) % 7 == 0) {
                System.out.println();
            }
        }
    }

    public static int getDaysInMonth(int year, int month) {
        int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        if (month == 2 && isLeapYear(year)) {
            return 29;
        }

        return daysInMonth[month - 1];
    }

    public static int getStartDayOfWeek(int year, int month) {
        int totalDays = 0;

        for (int y = 1900; y < year; y++) {
            totalDays += isLeapYear(y) ? 366 : 365;
        }

        for (int m = 1; m < month; m++) {
            totalDays += getDaysInMonth(year, m);
        }

        return (totalDays + 1) % 7;
    }

    public static boolean isLeapYear(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }
}

这个代码实现了一个简单的万年历程序。用户可以输入年份和月份,然后程序会打印出对应的日历。程序使用了getDaysInMonth()函数来计算每个月的天数,getStartDayOfWeek()函数来计算每个月的第一天是星期几,isLeapYear()函数来判断是否是闰年。最后,printCalendar()函数根据上述计算结果打印出日历。

0
看了该问题的人还看了