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 不是闰年...第二个 && 条件中传递的值是什么...(year % 100 !=0)
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);
}
}
编译这个程序打印1900
不是闰年怎么办????这里我什至不检查它是否能被 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
我给你的另一个建议是只使用公历 http://download.oracle.com/javase/6/docs/api/java/util/GregorianCalendar.html找到你想要的:
GregorianCalendar cal = new GregorianCalendar();
System.out.println( cal.isLeapYear(1900) );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)