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

标签 java if-statement

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/

相关文章:

python-3.x - 多个 if 条件与一个条件的比较

java - 如何管理 Java 计时器任务?

java - JPA中的外键约束错误

java - 从 WSDL 生成 RESTful 代理

java 。我怎样才能提高性能?

带有 vector 的 C++ IF 评估操作数

java - 测试 X = A、B 或 C

java - Java 中的 Rijndael 支持

if-statement - zsh 如果帮助 : if ping unsuccessful

C 程序的函数似乎总是返回 true,但我不明白为什么