【发布时间】:2014-02-20 02:03:53
【问题描述】:
这是作业。
我正在尝试查找用户输入的一年中 1900 年 1 月 1 日(我们假设是星期一)和一年中的 12 月 31 日之间的每个月的第一天发生的周日登陆。日历扩展是禁止使用的。
我以正确的格式返回日期,但它们与我们的讲师提供的示例代码不匹配。
在给定的示例中,输入 1902 应返回:
1900 年 4 月 1 日
1900 年 7 月 1 日
1901 年 9 月 1 日
1901 年 12 月 1 日
1902 年 6 月 1 日
对于 1902,我的代码返回:
1900 年 3 月 1 日
1901 年 1 月 1 日
1901 年 4 月 1 日
1901 年 5 月 1 日
1902 年 2 月 1 日
1902 年 6 月 1 日
1902 年 7 月 1 日
import java.util.Scanner;
public class Sundays {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter the ending year: ");
int userInputYear = reader.nextInt();
int[] orderedLengthOfMonthsArray = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] orderedNamesOfMonthsArray = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int month = 0;
int dayOfWeek = 1; // initialized to MONDAY Jan 1, 1900 -- Sunday would be #7
int dayOfMonth = 1;
for (int year = 1900; year <= userInputYear; year++) {
for (month = 0; month < orderedLengthOfMonthsArray.length; month++) {
for (dayOfMonth = 1; dayOfMonth <= orderedLengthOfMonthsArray[month]; dayOfMonth++) {
dayOfWeek++;
if (dayOfMonth == 1 && dayOfWeek == 7) {
System.out.println(dayOfMonth + " " + orderedNamesOfMonthsArray[month] + " " + year);
}
if (dayOfWeek == 8) {
dayOfWeek = 1;
}
}
}
}
}
}
【问题讨论】:
-
你也忽略了闰年。
-
我应该提到我们假设没有闰年。