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

6 Answers6

62

continue

while(rs.next())
  {
    if(f.exists() && !f.isDirectory())
      continue;  //then skip the iteration
     
     else
     {
     //proceed
     }
  }
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
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.

Quetzalcoatl
  • 3,037
  • 2
  • 18
  • 27
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

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
7

You're looking for the continue; statement.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
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.

Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
4
while (rs.next())
{
  if (f.exists() && !f.isDirectory())
    continue;

  //proceed
}
kol
  • 27,881
  • 12
  • 83
  • 120