Reputation: 1
I have written a program to calculate a leap year. The second part is where i have to print the number of years to the next leap year if the year is not a leap year. For 2097 ,the output shows 3 years untill next leap but its supposed to be 7 years. I think i have made a mistake with the code in the last line. Please help me out. This is my code so far.
public static void main(String[] args) {
// TODO code application logic here
int year = 2093;
if((year%4==0) && year%100!=0){
System.out.println(year + " is a leap year.");
}
else if ((year%4==0) && (year%100==0)&& (year%400==0)) {
System.out.println(year + " is a leap year.");
}
else {
System.out.println(year + " is not a leap year");
System.out.println(4-(year%4) + " years untill next leap year");
}
Upvotes: 0
Views: 2033
Reputation: 14276
Main code:
int year = 2093;
if (isLeapYear(year) {
System.out.println(year + " is a leap year");
} else {
int moreYears = nextLeapYear(year) - year;
System.out.println(moreYears + " more years until next leap year");
}
Check if a year is a leap year:
public boolean isLeapYear(int year)
{
if (year % 4 != 0)
return false;
else if (year % 100 != 0)
return true;
else if (year % 400 != 0)
return false;
else
return true;
}
Get next leap year:
public int nextLeapYear(int year)
{
while( !isLearpYear(year) )
year++;
return year;
}
Upvotes: 1
Reputation: 178243
Your leap year determination appears correct. However, you are calculating the next leap year based on the incorrect "every 4 years is a leap year" rule with this expression:
4-(year%4)
You can find the next leap year by the following:
year
. Use the same logic you have already written to determine if it's a leap year.You will find it useful to place your if
logic in a separate method to avoid the repetition of code and logic.
Upvotes: 1