简体   繁体   English

Java - for循环中的死代码

[英]Java - dead code in for loop

I'm getting a dead code warning in a for loop at i++ . 我在i++的for循环中收到了死代码警告。 Why do I get that, and how do I solve this problem? 为什么我会这样做,我该如何解决这个问题?

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;    
}

You always exit the loop immediately, hence i never gets incremented. 你总是立即退出循环,因此i永远不会增加。

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

should be 应该

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

In the first version you have an empty clause following the if statement (due to the first semi-colon). 在第一个版本中,if语句后面有一个空子句(由于第一个分号)。 Consequently the return false always executes. 因此return false总是执行。 You exit the method, and the i++ never executes. 退出方法, i++永远不会执行。

if语句后删除分号。

Problem is in this line: 问题在于这一行:

if(p % i == 0); 

Remove semicolon and try again 删除分号,然后重试

If your code is expanded then it will become 如果您的代码已扩展,那么它将成为

     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;    
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM