首页 > 解决方案 > 为什么我的 if(else if) 语句被忽略?

问题描述

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 然后停止。

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

标签: javaif-statement

解决方案


您的第三个if条件缺少一个else(但也可以很容易地成为一个else块)。喜欢,

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

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

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

推荐阅读