以下是一個簡單的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()
函數根據上述計算結果打印出日歷。