首先,if if((year< 1582)==(year%4 == 0))检查布尔相等性.我想你想要if((年< 1582)&&(年%4 == 0))但我担心仍然无法修复你的逻辑. 我建议你先创建一个方法.第一部分应该测试年份是否小于1582年.如果是,如果它是4的倍数则返回true.第二部分在
Wikipedia here中有详细描述.将它放在一起就像是,
private static boolean isLeapYear(int year) {
if (year < 1582) {
return (year % 4 == 0);
}
/*
* Rest of algorithm from: http://en.wikipedia.org/wiki/Leap_year
*/
if (year % 4 != 0) {
/*
* if (year is not divisible by 4) then (it is a common year)
*/
return false;
} else if (year % 100 != 0) {
/*
* else if (year is not divisible by 100) then (it is a leap year)
*/
return true;
}
/*
* else if (year is not divisible by 400) then (it is a common year)
* else (it is a leap year)
*/
return (year % 400 == 0);
}
然后你可以使用printf输出结果,
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
System.out.printf("%d %s leap year", year, isLeapYear(year) ? "is a"
: "is not a");
}
最后,您的原始代码可以像 –
if (year < 1582 && year % 4 == 0)
System.out.println(year + " is a leap year");
else if (year < 1582)
System.out.println(year + " is not a leap year");
else if (year >= 1582 && (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");