Why is my leap year algorithm not working (Java)?

2020-04-08 13:38发布

问题:

Here is what I have:

Scanner input = new Scanner(System.in);
    System.out.print("Enter a year: ");
    int Year = input.nextInt();
    System.out.print("Enter a month (first three letters with the first"
            + " letter uppercase): ");
    String Month = input.next();

    String ThirtyOne = "Jan" + "Mar" + "May" + "Jul" + "Aug" + "Oct" + "Dec";
    String DaysThirtyOne = ThirtyOne.substring(21) + "31";

    String Thirty = "Apr" + "Jun" + "Sep" + "Nov";
    String DaysThirty = Thirty.substring(12) + "30";

    String TwentyEight = "Feb";
    String DaysTwentyEight = TwentyEight.substring(3) + "28";
    String DaysLeapYear = TwentyEight.substring(3) + "29";


    boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) && (Year % 400 == 0));

    if (ThirtyOne.contains(Month)) {
        System.out.println(Month + " " + Year + " has " + DaysThirtyOne 
                + " days in it.");
    }
    if (Thirty.contains(Month)) {
        System.out.println(Month + " " + Year + " has " + DaysThirty 
                + " days in it.");
    }
    if(TwentyEight.contains(Month)) {
        System.out.println(Month + " " + Year + " has " + DaysTwentyEight 
                + " days in it.");
    }
    if (isLeapYear) {
        System.out.println(Month + " " + Year + " has " + DaysLeapYear 
                + " days in it.");
    }

I am new to programming so I wouldn't be surprised if this code looks immature. Anyways, I have the user input a year and a month (first three letters). I created a boolean variable for a leap year that says whatever year the user inputs needs to be divisible by 4, 100, and 400. Then, I created an if statement for if it is a leap year to print out "Feb (whatever year the user inputs) has DaysLeapYear in it." I think I have something wrong with my algorithm because if I were to take out the if statement of TwentyEight and just kept the leap year if statements, the computer doesn't even print out how many days Feb would have if it was a leap year. Again, I think I'm going wrong in the algorithm, but it could be somewhere else and I was hoping for another look at this to see if someone sees something I am not since I am new to this after all.

回答1:

Firstly your isLeapYear condition needs to change.

boolean isLeapYear = ((Year % 4 == 0) && (Year % 100 != 0) || (Year % 400 == 0));

Next your if(TwentyEight.contains(Month)) for this need to change to consider leap year.

if(TwentyEight.contains(Month) && !isLeapYear) {
        System.out.println(Month + " " + Year + " has " + DaysTwentyEight
                + " days in it.");
}