简体   繁体   中英

Java program : Leap Year Calculator

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");
    }

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:

  1. Start with the next year after year . Use the same logic you have already written to determine if it's a leap year.
  2. If it's not, keep incrementing that "next year" value until you do find 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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM