Skip numbers in for-loop

Karan Gandhi :

I am trying to skip values using a for loop. Something like

for (int i = 32; i <= 255 /* - but skip 128 to 159 */; i++) 
{
    char ascii = (char) i;
    System.out.println(ascii);
}

Any suggestions?

Adam :
if(i >= 128 && i <= 159){
  // Will skip all these values.
  continue;
}

You can use the continue keyword within any loop in Java which will cause the control flow to jump back up to the immediate parent loop. So in your case, for all values of i between 128 and 159 the code block beneath will never be executed. Alternatively, if you don't like this solution then you could write two for loops and exclude the range between them, however this is arguably more simple to read and gives you more flexibility if you wish to skip multiple ranges or impose more specific conditions on when to skip values of i.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110685&siteId=1