【问题标题】:Why isn't my for loop looping? My for loop line is considered dead code为什么我的 for 循环不循环?我的 for 循环行被认为是死代码
【发布时间】:2016-05-27 11:58:00
【问题描述】:

我不确定为什么 Eclipse 说“i++”是死代码以及为什么 i 没有被递增。

for(int i = 0; i < holdings.length; i++)
            {
                if(holdings[i].holdingID.equals(userHoldingIDInput) == true)
                {
                    holdings[i].print();
                    System.out.println();
                    return;
                }
                else
                {
                    System.out.println("The Holding ID you entered was not found,"
                            + " please try again." + "\n");
                    return;
                }
            }

有人可以向我解释我做错了什么并提供解决方案吗?谢谢!

【问题讨论】:

  • 注意:if (something == true) 是多余的:你可以写if (something)
  • @AndyTurner 我忘记删除了,谢谢。

标签: java for-loop


【解决方案1】:

条件中的两个分支都以返回结束:

if (...) {
  // ...
  return;
} else {
  // ...
  return;
}

所以i++ 永远不会增加。

注意basic for statement 的一般结构是:

for ( ForInit ; Expression ; ForUpdate ) Statement

这是equivalent to the while loop:

{
  ForInit;
  while (Expression) {
    Statement;
    ForUpdate;
  }
}

所以如果Statement 无条件返回,ForUpdate 将永远不会执行,因此它已被正确识别为死代码。


我不确定你到底打算做什么,但我认为你的 else 分支实际上应该在循环之外:

for(int i = 0; i < holdings.length; i++) {
  if (holdings[i].holdingID.equals(userHoldingIDInput)) {
    // ...
    return;
  }
}
System.out.println("The Holding ID you entered was not found,"
                        + " please try again." + "\n");
return;  // Might be unnecessary; depends upon what follows.

【讨论】:

  • 噢噢噢噢。我添加了退货,因为我认为它解决了我之前遇到的问题,但它只会造成另一个问题。谢谢!
  • 即使你不知道我打算对代码做什么,将 else 分支放在 for 循环之外并在 if 语句中保留 return 实际上解决了我遇到的其他一些问题再次感谢您!
  • @C.Smith 不客气。请考虑接受答案。
【解决方案2】:

您正在从两种情况中恢复。 i++ 将在循环的下一次迭代中得到评估。因为这永远不会发生,你的 IDE 建议它是一个死代码。

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多