-2

I tried the year 1900, which in my program prints its a leap year, however, 1900 shouldnt be a leap year. Can someone help me with the logic behind the if condition?

class LeapYearTrial{
public static void main(String[]args){

   String s;
   int year;

   s = JOptionPane.showInputDialog("Enter year");
   year = Integer.parseInt(s);

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

      JOptionPane.showMessageDialog(null, year + " is a leap year"); 

   } else {

      JOptionPane.showMessageDialog(null, year + " is not a leap year");
      }
   }
}
Zerenity
  • 107
  • 6
  • I think you might be missing some logic steps. I found [this](https://beginnersbook.com/2017/09/java-program-to-check-leap-year/), it might be able to help you. Edit: Looks like you need to re-order your if statement, and all the conditions must be true. `year % 4`, `year % 100`, `year % 400` if all those are true and in order, it's a leap year – Sterling Archer Feb 25 '20 at 18:16
  • 1
    Does this answer your question? [Java Code for calculating Leap Year](https://stackoverflow.com/questions/1021324/java-code-for-calculating-leap-year) – Alessandro Mandelli Feb 25 '20 at 18:19
  • yep, got it , thanks! – Zerenity Feb 25 '20 at 18:31

1 Answers1

0

Your statement is not working in quite the way you expect it to:

year % 100 == 0 AndAlso
year % 400 == 0 OrElse
year % 4 == 0

For the year 1900, this produces the following:

true AndAlso
false OrElse
true

Which gives the outcome true.

You could use something like this instead:

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

This will return true only where the year is divisible by 400, or is divisible by 4 and not by 100.

Martin
  • 16,093
  • 1
  • 29
  • 48
  • got it got it, I had the wrong conditions. I interpreted "Leap Years are any year that can be evenly divided by 4. A year that is evenly divisible by 100 is a leap year only if it is also evenly divisible by 400." I dont know if that sentence above is badly written, because i interpreted it as that ANY YEAR that is divisible by 4 is a leap year without any other following conditions for that divisible by 4 condition. – Zerenity Feb 25 '20 at 18:27