简体   繁体   English

哪个leap年公式是最佳选择?

[英]which leap year formula is the best option?

I am working with a code that determines whether a year is a leap year or not. 我正在使用确定一年是否为a年的代码。 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. 版本1是正确的。 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) 如果您不想重新发明轮子,则java.util.GregorianCalendar已经具有实用程序方法: isLeapYear(year)

for (int year = 1997; year <= 2015; year++) {
    System.out.println(String.format("%d %b", year, new GregorianCalendar().isLeapYear(year)));
}

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. 另外,请注意,我只是简化了return语句,以便我们不执行不必要的变量分配。

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 % 100 == 0 && year % 400 == 0))可以重写为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). year % 100 != 0 || year % 400 == 0 ,因为在第二个or分支中,隐含year % 100 == 0 (否则我们将与第一个分支短路)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM