我是编程和java的新手,我正在努力解决以下问题:在二十世纪的第一个月(1901年1月1日至2000年12月31日),有多少个星期日下降?
这是我的代码:
int count, sum = 0;
for (int i = 1901; i < 2001; i++) {
LocalDate test = LocalDate.of(i, 1, 1);
sum += test.lengthOfYear();
}
for (int i = 1; i < sum; i++) {
LocalDate date1 = LocalDate.of(1901, 1, 1);
date1 = date1.plusDays(i);
if (date1.getMonth() == JANUARY && date1.getDayOfWeek() == SUNDAY) {
count++;
}
}
System.out.println(count);
Run Code Online (Sandbox Code Playgroud)
如果我打印结果,它似乎工作正常.
我的结果是443,但正确的答案是171.我做错了什么?
谢谢!
MC *_*ror 12
我怀疑443是二十世纪一月份的星期日总数.这是因为你走过了二十世纪所有可能的日子,然后检查当前月份是否是1月,当天是否是星期日.
这不是你想要的.
我会用另一种方法:
代码可能会快得多.
// Each year
for (int y = 1901; y < 2001; y++) {
// Each month of the year
for (int m = 1; m <= 12; m++) {
if (LocalDate.of(y, m, 1).getDayOfWeek() == DayOfWeek.SUNDAY) {
count++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
PS:如果您改为date1.getMonth() == JANUARY,您的代码将是正确的date1.getDayOfMonth() == 1.然而,这是非常低效的,因为它检查二十世纪的每一天,而它只需要检查每个月的第一天.上述代码在我的机器上快了大约40倍.
除了已被标记的错误之外,您可以重新考虑您的设计并使用看起来更适合您的用例的YearMonth类,而不是LocalDate:
public static void main(String[] args) {
YearMonth start = YearMonth.of(1901, 1);
YearMonth end = YearMonth.of(2000, 12);
int count = 0;
for (YearMonth ym = start; !ym.isAfter(end); ym = ym.plusMonths(1)) {
//is first day of month a sunday?
if (ym.atDay(1).getDayOfWeek() == SUNDAY) count ++;
}
System.out.println(count); //171
}
Run Code Online (Sandbox Code Playgroud)
我看到一些错误:
public static void main(String[] args) {
int count, sum = 0;
for (int i = 1901; i < 2001; i++) { // There is a mistake here, I dont know what you want to compute in this loop!
LocalDate test = LocalDate.of(i,1,1);
sum += test.lengthOfYear();
}
for (int i = 1; i < sum; i++) {
LocalDate date1 = LocalDate.of(1901,1,1); // There is a mistake here, date1 must be outside of this loop
date1 = date1.plusDays(i); // There is a mistake here, plusDays why??
if(date1.getMonth() == JANUARY && date1.getDayOfWeek() == SUNDAY) { // There is a mistake here, why are you cheking this: date1.getMonth() == JANUARY ?
count++;
}
}
System.out.println(count);
}
Run Code Online (Sandbox Code Playgroud)
一个简单的解决方案:
public static void main(String[] args) {
int count = 0;
LocalDate date1 = LocalDate.of(1901, Month.JANUARY, 1);
LocalDate endDate = LocalDate.of(2001, Month.JANUARY, 1);
while (date1.isBefore(endDate)) {
date1 = date1.plusMonths(1);
if (date1.getDayOfWeek() == DayOfWeek.SUNDAY) {
count++;
}
}
System.out.println(count);
}
Run Code Online (Sandbox Code Playgroud)