私はEclipseでJavaを使用してこのプログラムを作成しました。
コメントアウトのセクションで説明した式を利用することができました。
forループを使用すると、そのコードで満足している1年の各月を反復処理でき、クリーンでスムーズに見えます。変数にフルネームを付けてすべてを読みやすくすることもできますが、基本的には数式を使用しているだけです:)
私の問題は、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;
}
}
}
}