Search code examples
javaleap-year

Leap Year Program


import java.util.*;
public class LeapYear
{
    public static void main (String[]args)
    {
        Scanner scan= new Scanner (System.in);
        System.out.println("Please enter in the year");
        int year=scan.nextInt();
        if (year % 4 ==0)
        {
            { 
                if (year % 100 ==0);
                else 
                    System.out.println("The year,"+year+",is a leap year!");
            }
            if(year % 400==0)
                System.out.println("The year, "+year+",is a leap year!");
        }
        else
            System.out.println("The year, "+year+",is not a leap year!");
    }
}

Hey everyone! Above is my code for a leap year program- It seems to work well, except whenever I enter a number such as 3000 or 300, the JVM just stops and shuts the terminal window. Could someone please guide as to why it's not accepting these numbers (Also, please forgive me that my code is not formatted properly- I'm new and trying to do the best I can) NOTE: It is displaying all the right answers when I test 1900, 1996, 2004, 164, and 204 as years. It will simply not accept 300 or 3000. Thanks Again!


Solution

  • You asked that we forgive your formatting, but it is your formatting that is leading you to miss the problem. Especially when you are first starting out, you will find it most helpful to understand what's going on if you are extremely diligent in your formatting. Suggestion: always include the braces, even when they are optional, and always provide the 'else' portion of every 'if' statement. Thus:

    if (condition) {
        action;
    } else {
        alternative action;
    }
    

    In your case, you will see in your lines 11 and 12 where you have syntacticly correct code, but very likely not what you meant. The opening brace on line 11 seems out of place and the semicolon at the end of line 12 is simply taking the place of the "action" that would take place if that condition were true.

    if ((year % 4) == 0) {
        // could be a leap year
        if ((year % 100) == 0) {
            // could be a leap year too
            if ((year % 400) == 0) {
                println("yes, this is a leap year ... divisible by 4, 100, AND 400");
            } else {
                // not a leap year ... divisible by 4 and 100, but NOT 400
            }
        } else {
            println("yes, this is a leap year ... it's divisible by 4 but not 100");
        }
    } else {
        // absolutely not a leap year
    }