0

I am trying to solve a simple assignment from a course I have enrolled in, but it's not working for some reason.

Assignment says: "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."

When I run the code I get the message: "With input 1604 you should print "The year is a leap year", but you printed "Type a year: The year is not a leap year." "

This is my code:

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

    if((year % 4 == 0) && (year % 100 == 0 && year % 400 == 0)) {
        System.out.println("The year is a leap year.");
    }else {
        System.out.println("The year is not a leap year.");
    }
}

}

Ivan S.
  • 3
  • 2
  • Use a debugger to see the values of `year % 4`, `year % 100` and `year % 400`. – Andy Turner May 29 '17 at 19:07
  • 1
    Just *think* about what happens for the input 4, is it a leap year, what does the code output? Dont start with weird cases like 1604, start with the simple ones and check why even they already fail. – luk2302 May 29 '17 at 19:08
  • Are you sure that your program is supposed to print `"Type a year: "`? – tobias_k May 29 '17 at 19:09
  • Learn how to search properly. This link was the first hit from Google. – duffymo May 29 '17 at 19:09
  • Thank you all for answering. I am a total beginner and just joined SO, so sorry for duplicated post. Of course, I found what I was looking for in previous question that was posted before. – Ivan S. May 29 '17 at 19:16
  • you can short it also: private static Boolean isLeapYear(int year) { return year % 4 == 0 ? (year % 100 == 0 ? ( year % 400 == 0 ? true : false) : true) : false ; } – Ravindra Kumar May 29 '17 at 19:52

1 Answers1

1

if((year % 4 == 0) && (year % 100 == 0 && year % 400 == 0) uses && it should be ||. It should be if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)

1604 is divisible by 4 but since you use &&, it also checks if its divisible by 100 and 400 which it isn't.

TGKL
  • 312
  • 1
  • 14