欢迎访问宙启技术站
智能推送

在Java中如何使用函数实现一个简单的日历功能?

发布时间:2023-08-05 02:11:05

在Java中,我们可以使用函数来实现一个简单的日历功能。下面是一个使用函数实现日历功能的示例代码:

import java.util.Scanner;

public class CalendarFunction {
    // 函数:判断某年是否是闰年
    public static boolean isLeapYear(int year) {
        if (year % 400 == 0) {
            return true;
        } else if (year % 100 == 0) {
            return false;
        } else if (year % 4 == 0) {
            return true;
        } else {
            return false;
        }
    }

    // 函数:获取某月的天数
    public static int getDaysInMonth(int year, int month) {
        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 每个月的天数
        if (month == 2 && isLeapYear(year)) {
            return 29;
        } else {
            return days[month - 1];
        }
    }

    // 函数:获取某年的      天是星期几
    public static int getFirstDayOfWeek(int year) {
        int day = 1; // 日期从1号开始
        int month = 1; // 月份从1月开始
        int[] days = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; // Zeller公式中的月偏移量
        if (month < 3) {
            year--;
        }
        int firstDayOfWeek = (year + year / 4 - year / 100 + year / 400 + days[month - 1] + day) % 7;
        return firstDayOfWeek;
    }

    // 函数:打印日历
    public static void printCalendar(int year, int month) {
        int firstDayOfWeek = getFirstDayOfWeek(year);
        int daysInMonth = getDaysInMonth(year, month);
        
        // 打印月份和星期几的标题
        System.out.println("-----------------------------");
        System.out.printf("     %d年%d月
", year, month);
        System.out.println("-----------------------------");
        System.out.println("日 一 二 三 四 五 六");

        // 打印空白日期
        for (int i = 0; i < firstDayOfWeek; i++) {
            System.out.print("   ");
        }

        // 打印日期
        for (int day = 1; day <= daysInMonth; day++) {
            System.out.printf("%2d ", day);
            if ((day + firstDayOfWeek) % 7 == 0) { // 每7天换行
                System.out.println();
            }
        }
        System.out.println("
-----------------------------");
    }

    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);
    }
}

上述代码中,我们定义了四个函数来实现日历的功能:

1. isLeapYear函数用于判断某年是否为闰年,根据闰年的定义来判断。

2. getDaysInMonth函数用于获取某年某个月的天数,如果是闰年的二月就返回29天,否则返回相应的天数。

3. getFirstDayOfWeek函数用于计算某年的 天是星期几,这里使用了Zeller公式来计算,具体可参考[Zeller's Congruence](https://en.wikipedia.org/wiki/Zeller's_congruence)。

4. printCalendar函数用于打印日历,首先打印月份和星期几的标题,然后根据计算出的 天是星期几和每个月的天数来进行打印。

main函数中,我们使用Scanner类来获取用户输入的年份和月份,并调用printCalendar函数来打印日历。

以上代码是一个简单的日历实现,可以根据用户输入的年份和月份来打印对应的日历。