The code works when the first year is a leap year so if I said the year was 2004 it would return 2008, but when the starting year is not a leap year, it returns nothing. How would I output that if, for ex: the given year was 2001, 2002, or 2003, the next leap year would be 2004. I know the while loop makes sense but I don't know what to put inside it. ALSO I can only use basic java formatting so no inputted classes like java.time.Year
public static boolean leapYear(int year) {
boolean isLeap = true;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
isLeap = true;
else
isLeap = false;
} else
isLeap = true;
} else {
isLeap = false;
}
return isLeap;
}
public static int nextLeapYear(int year) {
int nextLeap = 0;
if (leapYear(year)) {
nextLeap = nextLeap + 4;
} else {
while (!leapYear(year)) {
nextLeap++;
}
nextLeap += 1;
}
year += nextLeap;
return year;
}
You can greatly simplify the function,
leapYear
as shown below:Demo:
Output:
Then, you can use it in the function,
nextLeapYear
as shown below:Output:
In production code, you should use the OOTB (Out-Of-The-Box) class,
java.time.Year
to deal with a year.Output:
Learn more about the modern date-time API at Trail: Date Time.