英文:
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 >= 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;
}
}
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 < 0 || year > 9999)
?
答案1
得分: 1
你只需要将你的第一个 if 语句改成:
if (year >= 0 && year <= 9999) {
-1200 总是小于 9999,所以它总是通过这个条件,因为有 ||
运算符。
英文:
you just have to change your first if statement to :
if (year >= 0 && year <= 9999) {
-1200 was always lower than 9999 so it was always going through this condition because of the ||
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论