Java: how many Sundays fell in the first month of the 20th century (January 1, 1901 to December 31, 2000)?

I am a novice in programming and Java. I am trying to solve the following problems:

This is my code:

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);
    date1 = date1.plusDays(i);
    if (date1.getMonth() == JANUARY && date1.getDayOfWeek() == SUNDAY) {
        count++;
    }
}
System.out.println(count);

If I print the result, it seems to work properly

My result is 443, but the correct answer is 171 What did I do wrong?

thank you!

Solution

I see some errors:

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);
        sum += test.lengthOfYear();
    }
    for (int i = 1; i < sum; i++) {
        LocalDate date1 = LocalDate.of(1901,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);
}

Simple solution:

public static void main(String[] args) {
    int count = 0;
    LocalDate date1 = LocalDate.of(1901,Month.JANUARY,1);
    LocalDate endDate = LocalDate.of(2001,1);
    while (date1.isBefore(endDate)) {
        date1 = date1.plusMonths(1);
        if (date1.getDayOfWeek() == DayOfWeek.SUNDAY) {
            count++;
        }
    }
    System.out.println(count);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>