Home > Back-end >  Logic hole with negative numbers in isALeapYear condition in java
Logic hole with negative numbers in isALeapYear condition in java

Time:11-15

public static void main(String[] args){
    boolean year = isLeapYear(9999);
    System.out.println("Is Leap Year: "   year);
}
public static boolean isLeapYear(int year){
    int rem4 = year % 4;
    int rem100 = year % 100;
    int rem400 = year % 400;
    if ((year >= 1 && year <= 9999) && (rem4 == 0) && (rem100 == 0 && rem400 == 0) || (rem100 != 0) && (rem4 == 0)){
        return true;
    }
    return false;
}

When I enter a negative year (so far only -1024) my range condition doesn't work. But if I enter any other negative leap year it works(-2020). So I don't know what I'm possibly missing, or if the structure of the algorithm is quite right. Any help will be appreciated.

What is expected is that when I enter a year that is not a leap year, and if it is a negative leap year, it returns false.

CodePudding user response:

Not exactly sure, but maybe it's because when || (rem100 != 0) && (rem4 == 0)) returns a true statement, your whole function returns true, negating the whole first part of your if-statement.

CodePudding user response:

As the || overrides the positive validation part, just add that same validation in the other part of the condition...

(year >= 1 && year <= 9999 && rem4 == 0 && rem100 == 0 && rem400 == 0 || year >= 1 && year <= 9999 && rem100 != 0 && rem4 == 0)
  • Related