英文:
Why else if doesnt do anything in this case
问题
我知道这可能是一个愚蠢的问题,但我几天前才开始学习,只是胡乱尝试,不太确定为什么这不起作用,有人可以解释一下吗?
我有一个简单的窗口和一个按钮,它可以通过 +1 添加点击次数,然后经过几次点击后会将它们相乘(这部分起作用),但是当它到达 "else if" 部分并且 count * 4 时,它就没有任何反应。
@Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("点击次数:" + count);
if (count > 5){
label2.setText("启动涡轮模式");
label.setText("涡轮点击次数:" + count*2);
} else if (count > 20){
label2.setText("启动超级涡轮模式");
label.setText("超级涡轮点击次数:" +count*4);
}
}
谢谢你的答复。
英文:
I know this might be silly question, but i just started learning few days ago and i was just messing around, and im not sure why this doesnt work, could someone please explain it to me ?
I got a simple window with button and it adds clicks by +1, then after few clicks it multiplies them (that part work) but when it get to "else if" and count * 4 it just doesnt do anything
@Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Number of clicks: " + count);
if (count > 5){
label2.setText("Turbo mode activate");
label.setText("Number of turbo clicks: " + count*2);
} else if (count > 20){
label2.setText("SuperTurbo mode activated");
label.setText("Number of superturbo clicks: " +count*4);
}
}
}
Thank you for answer
答案1
得分: 1
因为即使计数达到100,它仍然大于5,然后始终执行第一个代码块,否则如果永远没有机会。
在您的情况下,您可以说如果(计数<=20),则执行第一个代码块,否则{....}执行第二个代码块。
英文:
because even if the counts gets to 100 it is greater than 5 and then the first code block is always executed and else if never gets the chance.
In your case, you could say that if (count <= 20)
then do first block or else { .... }
execute the second block of code.
答案2
得分: 0
条件会按顺序进行评估。count > 5
会在 count > 20
之前始终为真:任何大于 20 的数也必定大于 5。
您可以将条件取反,以便稍后检查更一般的条件,而先检查更特定的条件。
if (count > 20) {}
else if (count > 5) {}
英文:
Conditions are evaluated in order. count > 5
will always be true before count > 20
: anything greater than 20 is also greater than 5.
You can inverse the conditions to check the more general conditions later and the more specific earlier.
if (count > 20) {}
else if (count > 5) {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论