實現輸入年月輸出該月日曆的萬年歷程序,詳細對比四種星期計算公式,提供可直接運行的完整 Java 代碼。
W = [Y-1] + [(Y-1)/4] - [(Y-1)/100] + [(Y-1)/400] + D
w = y + [y/4] + [c/4] - 2c + [26(m+1)/10] + d - 1
W = [y/4] + r(y/7) - 2r(c/4) + m' + d
W = (d + 2m + 3(m+1)/5 + y + y/4 - y/100 + y/400) mod 7
import java.util.Scanner;
public class PerpetualCalendar {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("☆☆☆☆☆☆☆☆☆☆歡迎使用萬年歷☆☆☆☆☆☆☆☆☆");
System.out.print("請輸入年份:");
int year = scan.nextInt();
System.out.print("請輸入月份:");
int month = scan.nextInt();
// 判斷閏年
boolean isLeap = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
System.out.println(year + "年是" + (isLeap ? "閏年" : "平年") + "!");
// 當月天數
int daysInMonth;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31; break;
case 4: case 6: case 9: case 11:
daysInMonth = 30; break;
case 2:
daysInMonth = isLeap ? 29 : 28; break;
default:
System.out.println("月份輸入錯誤!"); return;
}
System.out.println(month + "月有" + daysInMonth + "天。");
// 計算1號是星期幾 (通用公式)
int daysBeforeMonth = 0;
for (int m = 1; m < month; m++) {
switch (m) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysBeforeMonth += 31; break;
case 4: case 6: case 9: case 11:
daysBeforeMonth += 30; break;
case 2:
daysBeforeMonth += isLeap ? 29 : 28; break;
}
}
int week = (year - 1) + (year - 1)/4 - (year - 1)/100 + (year - 1)/400 + daysBeforeMonth;
week = 1 + week % 7; // 1=周日...7=周六
if (week == 7) week = 0; // 調整為 0=周日
// 打印日曆
System.out.println("日\t一\t二\t三\t四\t五\t六");
for (int i = 0; i < week; i++) System.out.print("\t");
for (int day = 1; day <= daysInMonth; day++) {
System.out.print(day + "\t");
if ((day + week) % 7 == 0) System.out.println();
}
}
}
輸入 2017 年 1 月,正確顯示 1 月 1 日為周日,31 天排列整齊。程式碼結構清晰,易於擴展為 GUI 版本或加入農曆/節氣功能。