加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 一个简单的闰年逻辑问题

发布时间:2020-12-15 02:03:55 所属栏目:Java 来源:网络整理
导读: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 !=
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);
    }
}

我作为我的输入传递了1900.第一个条件评估为真,因为它可以被4整除,但1900也应该被100整除…

为什么我得到1900年不是闰年….第二个&&条件…(年%100!= 0)

更新

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);

    }

}

编译这个程序打印1900不是leapYear How ????在这里,我甚至没有检查它是否可以被400整除.

解决方法

解释你的代码:

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

我给你的另一个建议就是使用GregorianCalendar找到你想要的东西:

GregorianCalendar cal = new GregorianCalendar();
System.out.println( cal.isLeapYear(1900) );

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读