我是编程和Java的新手,正在尝试解决以下问题:
在20世纪的1月1日(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);

如果我打印结果,它似乎工作正常。

我的结果是443,但正确的答案是171。我做错了什么?

谢谢!

最佳答案

我看到一些错误:

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);
}

一个简单的解决方案:
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);
}

10-07 18:59