我在 Eclipse 中使用 Java 编写了这个程序。
我能够使用我在注释掉的部分中解释的公式。
使用 for 循环,我可以遍历一年中的每个月,我对此代码感觉很好,对我来说它看起来干净流畅。也许我可以给变量全名以使所有内容更具可读性,但我只是在其基本本质中使用公式:)
那么我的问题是它不能正确计算像 2008 年这样的年份......闰年。
我知道如果 (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) 那么我们有闰年。
也许如果这一年是闰年,我需要从某个月份中减去一定数量的天数。
任何解决方案或某些方向都会非常感谢:)
package exercises;
public class E28 {
/*
* Display the first days of each month
* Enter the year
* Enter first day of the year
*
* h = (q + (26 * (m + 1)) / 10 + k + k/4 + j/4 + 5j) % 7
*
* h is the day of the week (0: Saturday, 1: Sunday ......)
* q is the day of the month
* m is the month (3: March 4: April.... January and Feburary are 13 and 14)
* j is the century (year / 100)
* k is the year of the century (year %100)
*
*/
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter the year: ");
int year = input.nextInt();
int j = year / 100; // Find century for formula
int k = year % 100; // Find year of century for formula
// Loop iterates 12 times. Guess why.
for (int i = 1, m = i; i <= 12; i++) { // Make m = i. So loop processes formula once for each month
if (m == 1 || m == 2)
m += 12; // Formula requires that Jan and Feb are represented as 13 and 14
else
m = i; // if not jan or feb, then set m to i
int h = (1 + (26 * (m + 1)) / 10 + k + k/4 + j/4 + 5 * j) % 7; // Formula created by a really smart man somewhere
// I let the control variable i steer the direction of the formual's m value
String day;
if (h == 0)
day = "Saturday";
else if (h == 1)
day = "Sunday";
else if (h == 2)
day = "Monday";
else if (h == 3)
day = "Tuesday";
else if (h == 4)
day = "Wednesday";
else if (h == 5)
day = "Thursday";
else
day = "Friday";
switch (m) {
case 13:
System.out.println("January 1, " + year + " is " + day);
break;
case 14:
System.out.println("Feburary 1, " + year + " is " + day);
break;
case 3:
System.out.println("March 1, " + year + " is " + day);
break;
case 4:
System.out.println("April 1, " + year + " is " + day);
break;
case 5:
System.out.println("May 1, " + year + " is " + day);
break;
case 6:
System.out.println("June 1, " + year + " is " + day);
break;
case 7:
System.out.println("July 1, " + year + " is " + day);
break;
case 8:
System.out.println("August 1, " + year + " is " + day);
break;
case 9:
System.out.println("September 1, " + year + " is " + day);
break;
case 10:
System.out.println("October 1, " + year + " is " + day);
break;
case 11:
System.out.println("November 1, " + year + " is " + day);
break;
case 12:
System.out.println("December 1, " + year + " is " + day);
break;
}
}
}
}