0

Directions: "A year is a leap year if it is divisible by 4. But if the year is divisible by 100, it is a leap year only when it is also divisible by 400.

Create a program that checks whether the given year is a leap year." I am having most trouble with getting the calculations part down. Here is my code:

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    int year;

    System.out.print("Type a year:");
    year=Integer.parseInt(reader.nextLine());

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

      System.out.println("The year a leap year.");
 }else       
       System.out.println("The year is not a leap year.");

}

I don't receive errors when I run the code, however, when I put such dates, 1600, 1601, and 1700 etc it says it is a leap year when it should not be. I'm very lost and any help will be greatly appreciated

1 Answers1

1

Try this:

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

ECLIPSE-MAN
  • 76
  • 1
  • 6
  • thank you, the code works 100%. Can you please explain what I did wrong that prevented my code to not print correctly. And the operator "!," I never really understood what it was meant for, can you explain how that "!" works in this case? Thank you again! :) – AMCgiftcard Jan 05 '20 at 06:58
  • @AMCgiftcard The order matters. In your case, you first checked whether ```year``` is divisible by 4 (which is always ```true``` for every number divisible by 100). Also, checking for equality in ```year % 100 == year % 400``` is not a good thing, since it returns ```true``` even for 1601 or 2003 (because remainder of division both by 100 and 400 is the same). In the code above it first checks if ```year``` is divisible by 4 *and* not divisible by 100. This means we are working with the first case only (the second being the numbers divisible by 100). – ECLIPSE-MAN Jan 05 '20 at 07:15
  • Oh, okay that makes a lot more sense! Thank you again! – AMCgiftcard Jan 05 '20 at 22:13