为什么在这种情况下使用“否则如果”不起作用

huangapple go评论64阅读模式
英文:

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 &lt;= 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 &gt; 5 will always be true before count &gt; 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 &gt; 20) {}
else if (count &gt; 5) {}

huangapple
  • 本文由 发表于 2020年10月13日 05:18:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64325474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定