GeoTeo :
I am new to programming and java and I am trying to solve the following problem: How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
Here 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, 1);
date1 = date1.plusDays(i);
if (date1.getMonth() == JANUARY && date1.getDayOfWeek() == SUNDAY) {
count++;
}
}
System.out.println(count);
If I print the results, it seems to be working fine.
My result is 443, but the correct answer is 171. What am I doing wrong?
Thank you!
David Pérez Cabrera :
I see some mistakes:
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);
}
A simple solution:
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);
}
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=458358&siteId=1