gpt4 book ai didi

java - 为什么我的 if(else if) 语句被忽略?

转载 作者:行者123 更新时间:2023-12-02 10:27:47 25 4
gpt4 key购买 nike

public void stackPower(int stackAmount)
{
super.stackPower(stackAmount);

if (this.amount == -1) {
this.amount = -2;
}
else if (this.amount == -2) {
this.amount = -3;
}
if (this.amount == -3) {
this.amount = -4;
}

}

在测试期间,值从 -1 到 -2 到 -4 到 -6 等。

我想要发生的事情:从-1到-2到-3再到-4,然后停止。

有人可以解释一下我在这里缺少什么以及如何解决我的问题吗?谢谢。

最佳答案

您的第三个 if 条件缺少 else (但也可以很容易地成为 else block )。就像,

if (this.amount == -1) {
this.amount = -2;
} else if (this.amount == -2) {
this.amount = -3;
} else {
this.amount = -4;
}

但是,我会通过调用 Math.max(int, int)简化逻辑,例如

this.amount = Math.max(-4, this.amount - 1);

关于java - 为什么我的 if(else if) 语句被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53799011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com