【问题标题】:Java - dead code in for loopJava - for 循环中的死代码
【发布时间】:2012-12-24 11:34:39
【问题描述】:

我在 i++ 的 for 循环中收到了死代码警告。为什么我会得到这个,我该如何解决这个问题?

public static boolean Method(int p) {
    for(int i = 2; i < p; i++) {  // here is the problem, at i++
        if(p % i == 0);         
            return false;
    }
    return true;    
}

【问题讨论】:

  • 这里的p值是多少?
  • 你骗了我!那个分号很难看……
  • @jmendeth 总是这样! :)

标签: java loops for-loop


【解决方案1】:

您总是立即退出循环,因此i 永远不会增加。

    if(p % i == 0);         
        return false;

应该是

    if(p % i == 0)       
        return false;

在第一个版本中,if 语句后面有一个空子句(由于第一个分号)。因此return false 总是执行。您退出该方法,i++ 永远不会执行。

【讨论】:

    【解决方案2】:

    删除if 语句后的分号。

    【讨论】:

      【解决方案3】:

      问题出在这一行:

      if(p % i == 0); 
      

      删除分号并重试

      【讨论】:

        【解决方案4】:

        如果你的代码被扩展,那么它将变成

             public static boolean Method(int p) {
                for(int i = 2; i < p; i++) {  // here is the problem, at i++
                    if(p % i == 0)
                    {
        
                    }
                   return false; //If you give return statement here then how it will work.
                }
                return true;    
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-14
          • 1970-01-01
          • 2013-09-03
          相关资源
          最近更新 更多