在Java中计算闰年是通过绕过一个else语句。

huangapple go评论81阅读模式
英文:

Calculate Leap Year in Java is bypassing an else statement

问题

以下是翻译好的代码部分:

public class LeapYear {

    public static void main(String[] args) {
        isLeapYear(2004);
    }

    public static boolean isLeapYear(int year) {
        boolean status = true;

        if (year >= 0 || year <= 9999) {
            if (year % 4 == 0){
                status = true;
                System.out.println("true");
            } else if (year % 100 == 0){
                status = true;
                System.out.println("true");
            } else if (year % 400 == 0) {
                status = true;
                System.out.println("true");
            } else {
                status = false;
                System.out.println("false");
            }

        } else if (year < 0 || year > 9999){
            status = false;
            System.out.println("false");
        }
        return status;
    }
}

请注意,我只提供了翻译好的代码部分,没有包括其他内容。如果你需要进一步解释或讨论代码问题,请随时提问。

英文:

There must be a bug somewhere in my 30 lines of code but I cannot find it and it's driving me nuts.

If I execute this code using isLeapYear(2004) I receive a true:

public class LeapYear {

    public static void main(String[] args) {
        isLeapYear(2004);
    }

    public static boolean isLeapYear (int year) {
        boolean status = true;

        if (year &gt;= 0 || year &lt;= 9999) {
            if (year % 4 == 0){
                status = true;
                System.out.println(&quot;true&quot;);
            } else if (year % 100 == 0){
                status = true;
                System.out.println(&quot;true&quot;);
            } else if (year % 400 == 0) {
                status = true;
                System.out.println(&quot;true&quot;);
            } else {
                status = false;
                System.out.println(&quot;false&quot;);
            }

        } else if (year &lt; 0 || year &gt; 9999){
            status = false;
            System.out.println(&quot;false&quot;);
        }
        return status;
    }
}

But if I run it for isLeapYear(-1200) it returns me a true as well but it shouldn't.

Why is my code bypassing else if (year &lt; 0 || year &gt; 9999) ?

答案1

得分: 1

你只需要将你的第一个 if 语句改成:

if (year >= 0 && year <= 9999) {

-1200 总是小于 9999,所以它总是通过这个条件,因为有 || 运算符。

英文:

you just have to change your first if statement to :

if (year &gt;= 0 &amp;&amp; year &lt;= 9999) {

-1200 was always lower than 9999 so it was always going through this condition because of the ||.

huangapple
  • 本文由 发表于 2020年4月9日 16:54:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/61117375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定