java - 星期几、java 和 Zeller 的同余!

标签 java

我正在根据一本教科书进行这个编程练习,其中给我们提供了一种计算星期几的算法,称为泽勒同余。那么你认为我可以获得与教科书中运行的示例相同的输出吗?它们与 2002 年第 3 个月和第 26 个月的某一天一致。样本会读回星期二。我已经进行了几个小时的修改和重写,但在周二之前却一事无成!

这是 Java 综合教科书 8e 的第 133 页,如果有人有的话...我是初学者,非常欢迎建设性的反馈!

Zeller's Congruence

您的建议将不胜感激:

import java.util.Scanner;

public class DayOfTheWeek {

   public static void main(String[] args) {

   // Set up the scanner...
   Scanner input = new Scanner(System.in);

   // Set up the day's of the week with 0 being Sat as per algorithm.           
   final String[] DAY_OF_WEEK = {"Saturday", "Sunday", "Monday", 
       "Tuesday", "Wednesday", "Thursday", "Friday"};

   // Get the year       
   System.out.print("Enter the year (e.g., 2002): ");             
   int year = input.nextInt();

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

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

   // According to the algorithm Jan is 13 & Feb 14...
   if (month == 1) month = 13;
   else if (month == 2) month = 14;

   // j Is the century.
   int j = year / 100;

   // k Is the year of the century.
   int k = year % 100 ;

   // Calculate
   double h = (month + ((26*(month + 1)) / 10) + k + (k / 4) +
           (j / 4) + (5 * j)) % 7;

   // Cast answer back to integer to get result from array
   int ans = (int)h;

   // Print result
   System.out.println("Day of the week is: " + DAY_OF_WEEK[ans]);

   }
}

最佳答案

看起来这行代码是错误的:

double h = (month + ((26*(month + 1)) / 10) + k + (k / 4) +
(j / 4) + (5 * j)) % 7;

该公式将添加到第一个表达式中,而不是。所以它应该看起来像这样:

double h = (day + ((26*(month + 1)) / 10) + k + (k / 4) +
(j / 4) + (5 * j)) % 7;

关于java - 星期几、java 和 Zeller 的同余!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6840020/

相关文章:

java - Goal Seek 在 groovy 中的实现

java - spring 的库(JAR)属性默认值

java - 编译时,我收到错误 : "unreachable statement". 如何解决该问题?

java - PhP 与 Java 哪个最适合中型到企业级 Web 应用程序?

java - 尝试使用 iText7 合并合并 pdf,但是当我打开最终合并的 pdf 时,它说无法加载 pdf 文档

java - 数组参数传递

java - 用整数创建日期然后转换回整数会在 JAVA 中失去精度吗?

java - 密集的 GC Activity 暂时关闭服务

java bash命令问题

java - 如何将 JSON 数据从 URL 读取到 XPage Java Bean