使用Zeller在Java中的同余来确定星期几

时间:2013-06-30 13:22:13

标签: java

我一直盯着我的Zeller的同余程序一小时,但我不知道我的逻辑错误在哪里。有人可以指出错误吗?谢谢!

// Implement the Zeller's congruence algorithm.
// To calculate the day of the week

import java.util.Scanner;

public class DayOfTheWeek {
    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);

        // Prompt the user to enter a year, month and a day
        System.out.print("Enter year (e.g., 2008): ");
        int year = input.nextInt();

        System.out.print("Enter month: 1-12: ");
        int month = input.nextInt();

        System.out.print("Enter the day of the month: 1-31: ");
        int day = input.nextInt();

        // Check if the month is January or February
        // If the month is January and February, convert to 13, and 14,
        // and year has to -1. (Go to previous year).
        if (month == 1 || month == 2) {
            month += 12;
            year--;
        }

        // Compute the answer
        int k = year % 7; // The year of the century
        int j = (int)(year / 100.0); // the century
        int q = day;
        int m = month;
        int h = (q + (int)((26 * (m + 1)) / 10.0) + k + (int)(k / 4.0) 
                + (int)(j / 4.0) + (5 * j)) % 7;

        String result = "Day of the week is ";

        //Display the name of the day of the week
        if (h == 0) 
            System.out.print(result + "Saturday");
        else if (h == 1)
            System.out.print(result + "Sunday");
        else if (h == 2)
            System.out.print(result + "Monday");
        else if (h == 3)
            System.out.print(result + "Tuesday");
        else if (h == 4)
            System.out.print(result + "Wednesday");
        else if (h == 5)
            System.out.print(result + "Thursday");
        else
            System.out.print(result + "Friday");
    }
}

3 个答案:

答案 0 :(得分:2)

int k = year % 7; // The year of the century

您可能需要% 100

另外,你要混合两个公式。如果您正在使用软件(as provided by Wikipedia)进行最佳实施,请尝试以下方法:

// ...
// remove j and k
int y = year;
// ...
// reformatted for readability
int h = (q +
         (int)((26 * (m + 1)) / 10.0) +
         y +
         (int)(y / 4.0) +
//       changes after here
         6 * (int)(y / 100.0) +
         (int)(y / 400.0))
        % 7;

或者这个:

int h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0)
//                  ^^
           + (int)(j / 4.0) + (5 * j)) % 7;

您(可能是无意中)使用第二个软件公式的开头和第一个软件公式的结尾,导致计算机无法混淆。

答案 1 :(得分:1)

int k = year % 7; // The year of the century

这不应该是% 100吗?

答案 2 :(得分:1)

String result = "The Day of the week of " + (i<10?("0" + i):(i)) + "/" 
//
+ (q<10?("0" + q):(q)) + "/" + j + (k<10?("0" + k):(k)) + " is ";

并不总是提供与

相同的结果
 scanf ("%s", &StudentName);

但我很感激并使用了您的意见,谢谢!

我也觉得这很有帮助:

//输出原始年份输入(k <10?(“0”+ k):( k)),同样为月份和日期格式:mm / dd / yyyy;

scanf ("%49s", StudentName);