[java] How to skip a iteration/loop in while-loop

Is there an elegant way to skip a iteration in while-loop ?

What I want to do is

  while(rs.next())
  {
    if(f.exists() && !f.isDirectory()){
      //then skip the iteration
     }
     else
     {
     //proceed
     }
  }

This question is related to java

The answer is


while (rs.next())
{
  if (f.exists() && !f.isDirectory())
    continue;

  //proceed
}

You don't need to skip the iteration, since the rest of it is in the else statement, it will only be executed if the condition is not true.

But if you really need to skip it, you can use the continue; statement.


While you could use a continue, why not just inverse the logic in your if?

while(rs.next())
{
    if(!f.exists() || f.isDirectory()){
    //proceed
    }
}

You don't even need an else {continue;} as it will continue anyway if the if conditions are not satisfied.


Try to add continue; where you want to skip 1 iteration.

Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration. This allows us to bypass the rest of the statements in the current sequence, without stopping the next iteration through the loop.

http://www.javacoffeebreak.com/articles/loopyjava/index.html


You're looking for the continue; statement.