[英]Why does my code step into an else-if statement whose condition should be false?
I have a method that is supposed to return the seasons of the year depending upon the month and day. 我有一种方法应该根据月和日返回一年中的季节。 The first three times I call the method it works fine. 我调用该方法的前三次工作正常。 However, the fourth method returns spring when it should return fall. 但是,第四种方法在返回时会返回spring。
It should bypass the else-if statement for spring and continue down to fall but when I debug it, that is not what it does. 它应该绕过spring的else-if语句并继续下降但是当我调试它时,这不是它的作用。 it goes into that else-if and returns it. 它进入其他 - 如果并返回它。
I tried moving the months and dates around but no matter where I put it, it returns spring. 我尝试移动月份和日期,但无论我把它放在哪里,它都会恢复春天。 I cannot figure out why since the arguments do not meet the criteria for that particular statement. 我无法弄清楚为什么因为这些论点不符合该特定陈述的标准。
Here is my code: 这是我的代码:
public static void main(String[] args) {
System.out.println(season(1, 5));
System.out.println(season(4, 12));
System.out.println(season(7, 1));
System.out.println(season(10, 31));
}
public static String season(int month, int day) {
if(month >= 12 && day >= 16 || month <= 3 && day <= 15) {
return "winter";
} else if(month >= 3 && day >= 16 || month <= 6 && day <= 15) {
return "spring";
} else if(month >= 6 && day >= 16 || month <= 9 && day <= 15) {
return "summer";
} else {
return "fall";
}
}
Your program is doing exactly what you told it to. 你的程序正在完成你告诉它的程序。 When you call season(10, 31)
, you get to the test: 当你打电话给season(10, 31)
,你会参加考试:
if (month >= 3 && day >= 16 || ...)
which is true because the month is 10 and the day is 31 (both greater than their targets in this test). 这是真的,因为月份为10,而日期为31(均高于此测试中的目标)。 Clearly, this is not what you want. 显然,这不是你想要的。 So you have to make a slightly more complicated test: 所以你必须做一个稍微复杂的测试:
if (month == 3 && day >= 16 || month > 3 && month < 6 || month == 6 && day <= 15)
This tests the day only if the month is not the starting or ending month for spring. 仅当月份不是春季的开始或结束月份时, 才会测试当天。 Your other tests will need similar adjustments. 您的其他测试需要进行类似的调整。
You may find that you might like to add parentheses to your tests to help group them as suggested by other answers here, but due to the Java operator precedence, it is not strictly necessary in this case. 您可能会发现您可能希望在测试中添加括号以帮助按照其他答案的建议对其进行分组,但由于Java运算符优先级,在这种情况下并不是绝对必要的。
If you remove first half of your conditions it will work fine. 如果您删除了前半部分条件,它将正常工作。
public static String season(int month, int day)
{
if(month <= 3 && day <= 15)
{
return "winter";
}
else if(month <= 6 && day <= 15)
{
return "spring";
}
else if(month <= 9 && day <= 15)
{
return "summer";
}
else
{
return "fall";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.