I am working with a code that determines whether a year is a leap year or not. This is the function that I have
private boolean leapYear(int year)
{
boolean t = false;
if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
t = true;
return t;
}
the function works fine, but I am afried that it might have some bugs, that´s why I have this other option:
private boolean esBisiesto(int year)
{
boolean t = false;
if((year % 4 == 0)&&(year % 100!=0 ||(year % 100 == 0 && year % 400 == 0)))
t = true;
return t;
}
but I don´t know which one of them is the best option
Version 1 is correct. Actually there is no need for so many brackets:
boolean leapYear = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
will work fine
If you're not wishing to reinvent the wheel, java.util.GregorianCalendar already has a the utility method: isLeapYear(year)
for (int year = 1997; year <= 2015; year++) {
System.out.println(String.format("%d %b", year, new GregorianCalendar().isLeapYear(year)));
}
Or with Java 8:
return Year.isLeap(year);
And the code is open source: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/time/Year.java#Year.isLeap%28long%29
There are no apparent data bugs ; both methods will return the correct value for the correct year. If you're ever concerned about there being bugs in your code, test it! It's the fastest way to get feedback on a method that you want to be sure works, and if you keep the test around, you'll be able to ensure you don't accidentally break that method, either.
The trick now is to ensure that the expression is correct. For the second method, the real issue is that it's been overexpressed. It can be a statement shorter.
Let's start from the inside-out. Also, note that I've just shortcut the return statement so that we're not doing an unnecessary variable assignment.
boolean esBisiesto(int year) {
return year % 4 == 0 && (year % 100 != 0 || (year % 100 == 0 && year % 400 == 0));
}
The expression (year % 100 != 0 || (year % 100 == 0 && year % 400 == 0))
can be rewritten as year % 100 != 0 || year % 400 == 0
year % 100 != 0 || year % 400 == 0
, because in the second or
branch, it is implied that year % 100 == 0
(or we would have short-circuited with the first branch).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.