计算 Java 中的闰年绕过了 else 语句
Calculate Leap Year in Java is bypassing an else statement
我的 30 行代码中一定有错误,但我找不到它,这让我抓狂。
如果我使用 isLeapYear(2004)
执行此代码,我会收到 true
:
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;
}
}
但是如果我 运行 它 isLeapYear(-1200)
它 returns 我也 true
但它不应该。
为什么我的代码绕过了 else if (year < 0 || year > 9999)
?
您只需将第一个 if 语句更改为:
if (year >= 0 && year <= 9999) {
-1200 始终低于 9999,因此由于 ||
.
,它始终处于这种状态
我的 30 行代码中一定有错误,但我找不到它,这让我抓狂。
如果我使用 isLeapYear(2004)
执行此代码,我会收到 true
:
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;
}
}
但是如果我 运行 它 isLeapYear(-1200)
它 returns 我也 true
但它不应该。
为什么我的代码绕过了 else if (year < 0 || year > 9999)
?
您只需将第一个 if 语句更改为:
if (year >= 0 && year <= 9999) {
-1200 始终低于 9999,因此由于 ||
.