rosababy :
I have two sets of code. if I make a new variable inside the loop, the code works as it's suppose to.
public static int subsequentLeapYear(int year) {
for(int i =1; i < 9; i++) {
int nextYear = year + i;
if(isLeapYear(nextYear)) {
return nextYear;
}
}
return 0;
}
public static int subsequentYear(int year) {
for(int i = 1; i < 9; i++) {
year += i;
if(isLeapYear(year)) {
return year;
}
}
return 0;
}
}
System.out.println(subsequentYear(8));
System.out.println(subsequentLeapYear(8));
it's suppose to print 12. for the first one it prints 36 not 12. I can't figure out why it's printint 36.
Edit:
public static boolean isLeapYear(int year) {
if(year % 400 == 0) {
return true;
}
if(year % 100 != 0 && year % 4 == 0) {
return true;
}
return false;
}
Gabriele Mariotti :
It happens because:
int nextYear = year + i;
year
is always the same value.
ex:
i=1 -> nextYear = 8 +1 = 9;
i=2 -> nextYear = 8 +2 = 10;
While:
year += i;
year is not always the same value.
i=1 -> year = 8 +1 = 9;
i=2 -> year = 9 +2 = 11;