简体   繁体   中英

Java - dead code in for loop

I'm getting a dead code warning in a for loop at i++ . 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.

    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). Consequently the return false always executes. You exit the method, and the i++ never executes.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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