首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 萬年歷實現:多種星期計算算法與完整代碼

     編輯:Java 綜合教學

Java 萬年歷實現:多種星期計算算法與完整代碼

實現輸入年月輸出該月日曆的萬年歷程序,詳細對比四種星期計算公式,提供可直接運行的完整 Java 代碼。

四大星期計算公式對比

1. 通用公式

W = [Y-1] + [(Y-1)/4] - [(Y-1)/100] + [(Y-1)/400] + D

  • Y:年份,D:該日期在年內的累積天數(1月1日為1)
  • 結果對 7 取餘:0=周日,1=周一...6=周六

2. 蔡勒 (Zeller) 公式

w = y + [y/4] + [c/4] - 2c + [26(m+1)/10] + d - 1

  • c:世紀數(年份前兩位),y:年份後兩位
  • m:月份(3=3月...14=翌年2月),d:日期
  • 注意:1、2月視作上一年 13、14 月

3. 馮思琮改進公式

W = [y/4] + r(y/7) - 2r(c/4) + m' + d

  • r() 取餘,m' 為月份修正值(含閏年調整)
  • 查表法,適合心算

4. 基姆拉爾森公式 (推薦)

W = (d + 2m + 3(m+1)/5 + y + y/4 - y/100 + y/400) mod 7

  • 直接用年月日,無需調整月份,公式最簡潔
  • 結果:0=周一...6=周日(或按需映射)

完整 Java 實現 (採用通用公式)

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 版本或加入農曆/節氣功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved