Search code examples
javaleap-year

Creating Leap Year program (Century included)


I am in my first year so I am really a newbie and we have homework which is –

By definition a leap year is any year that is divisible by 4. However if a year is a century year it is only a leap year if it is divisible by 400. Write a Java program that will input a year and determine if the year is leap year of not.

Also, since a century year is not known, I have to calculate it also basing from the entered year. I have read an answer online which I think is correct – getting the first 2 digits of the year then add 1.

Can I use the if/else only?

I don’t know how to do this. Submission is a day after today. Please help!

My code looks like this and I know that it lacks the century year.

import java.util.Scanner;
import java.io.*;

class leapyear
{
        public static void main(String[] a)
    {
        Scanner in = new Scanner (System.in);
        int year, centuryyear;
        System.out.print("Please enter a year: ");
        year = in.nextInt();

        if ((year % 4 == 0) && centuryyear % 400 == 0)
            {
            System.out.println(year + " Is a Leap Year");
            year++;
            }   
        else
            {
            System.out.println(year + " Is not a leap year");
            year++;
            }
    }
}

Solution

  • You don't need to use a seperate "century year" variable. You just need to test the year to see if it meets the criteria. The criteria:

    Divisible by 4 and not divisible by 100 unless also divisible by 400

    You already know how to use % to test for these conditions so let's look at them individually:

    Year divisible by 4 would be: year % 4 == 0

    Not divisible by 100 would be: year % 100 != 0

    But divisible by 400 would be: year % 400 == 0

    So we need the first expression AND the second expression OR the third expression:

    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)