24

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
     }
  }
1
  • 1
    Why not just have an if with f.isDirectory()? Commented Feb 13, 2013 at 14:48

6 Answers 6

62

continue

while(rs.next())
  {
    if(f.exists() && !f.isDirectory())
      continue;  //then skip the iteration
     
     else
     {
     //proceed
     }
  }
Sign up to request clarification or add additional context in comments.

Comments

13

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.

3 Comments

You will need an || instead of && there.
Your inversing of the logic is not correct, you should have OR instead of AND
Oops, good spot guys, will amend that now.
9

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

Comments

7

You're looking for the continue; statement.

Comments

5

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.

Comments

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

  //proceed
}

Comments