Java – a simple leap year logic problem
•
Java
public class LeapYear {
public class LeapYear { public static void main(String[] args) { int year = Integer.parseInt(args[0]); boolean isLeapYear; // divisible by 4 isLeapYear = (year % 4 == 0); // divisible by 4 and not 100 isLeapYear = isLeapYear && (year % 100 != 0); // divisible by 4 and not 100 unless divisible by 400 isLeapYear = isLeapYear || (year % 400 == 0); System.out.println(isLeapYear); } }
I passed 1900 as my input The first condition evaluates to true because it can be divided by 4, but 1900 should also be divided by 100
Why did I get 1900 not a leap year Second & & condition... (year% 100! = 0)
to update
public class TestSample { public static void main(String[] args){ int leapYear = Integer.parseInt(args[0]); boolean isLeapYear; isLeapYear = (leapYear % 4 == 0) && (leapYear % 100 != 0); System.out.println("Its Leap Year" +isLeapYear); } }
Compile this program to print 1900 not leapyear how???? Here, I didn't even check if it could be divided by 400
Solution
Explain your code:
isLeapYear = (year % 4 == 0); // isLeapYear = true isLeapYear = isLeapYear && (year % 100 != 0); // year % 100 IS 0. so the second part evaluates to false giving // true && false which yields isLeapYear as false isLeapYear = isLeapYear || (year % 400 == 0); // this is just false || false // which evaluates to false
Another suggestion I give you is to use Gregorian calendar to find what you want:
GregorianCalendar cal = new GregorianCalendar(); System.out.println( cal.isLeapYear(1900) );
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码