首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的if(else if)语句被忽略了?

问为什么我的if(else if)语句被忽略了?
EN

Stack Overflow用户
提问于 2018-12-16 10:39:56
回答 3查看 281关注 0票数 0
代码语言:javascript
复制
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,然后停止。

谁能解释一下我在这里遗漏了什么,以及如何修复我的问题?谢谢。

EN

回答 3

Stack Overflow用户

发布于 2018-12-16 10:46:04

您的第三个if条件缺少一个else (但也可能是一个else块)。喜欢,

代码语言:javascript
复制
if (this.amount == -1) {
    this.amount = -2;
} else if (this.amount == -2) {
    this.amount = -3;
} else {
    this.amount = -4;
}

但是,我可以通过调用Math.max(int, int)来简化逻辑,比如

代码语言:javascript
复制
this.amount = Math.max(-4, this.amount - 1);
票数 1
EN

Stack Overflow用户

发布于 2018-12-16 10:55:42

代码语言:javascript
复制
    if (this.amount == -1) {
        this.amount = -2;
    }
    else if (this.amount == -2) {
        this.amount = -3;
    }

我认为else if子句永远不会执行,因为一旦执行了if子句,else子句就永远不会执行。

票数 0
EN

Stack Overflow用户

发布于 2018-12-16 12:12:11

只需将else if更改为if就可以解决这个问题。

你遇到的问题是,当你有一个if -语句和一个else-if时,如果我们进入if-语句,我们会跳过后续的else-if语句或else语句。

代码语言:javascript
复制
     public void stackPower(int stackAmount)
{
          super.stackPower(stackAmount);

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

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53799011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档