Continuing a Loop

Contact Us or call 1-877-932-8228
Continuing a Loop

Continuing a Loop

If you need to stop the current iteration of the loop, but continue the looping process, you can use the continue statement. Note that:

  • It is normally based on a condition of some sort.
  • Execution skips to the end of this pass, but continues looping.
  • It is usually a better practice to reverse the logic of the condition, and place the remainder of the loop under control of the if statement.

Example - a program to enter 10 non-negative numbers

Code Sample:

Java-Control/Demos/Continuer.java
import util.*;

public class Continuer {
  public static void main(String[] args) {
    int count = 0;
    do {
      int num = KeyboardReader.getPromptedInt("Enter an integer: ");
      if (num < 0) continue;
      count++;
      System.out.println("Number " + count + " is " + num);
    } while (count < 10);
    System.out.println("Thank you");
  }

/*
  // a better way

  public static void main(String[] args) {
    int count = 0;
    do {
      int num = KeyboardReader.getPromptedInt("Enter an integer: ");
      if (num >= 0) {
        count++;
        System.out.println("Number " + count + " is " + num);
      }
    } while (count < 10);
    System.out.println("Thank you");
  }
*/

}

A better way to handle the loop is shown in the commented out version of main - try removing the comment and comment out the original method.

But,continue is easier to use in nested loops, because you can label the level that will be continued

break and continue in Nested Loops

In normal usage, break and continue only affect the current loop; a break in a nested loop would break out of the inner loop, not the outer one

But, you can label a loop, and break or continue at that level. A label is a unique identifier followed by a colon character.

Try the following example as is, then reverse the commenting on the break lines

Code Sample:

Java-Control/Demos/BreakOuter.java
public class BreakOuter {
  public static void main(String[] args) {

    outer: for (int r = 0; r < 10; r++) {
      for (int c = 0; c < 20; c++) {
        double x = Math.random();

        //if (x < 0.02) break;
        if (x < 0.02) break outer;
        System.out.print((int) (x * 10) + " ");
      }
      System.out.println();
    }
    System.out.println("Done!");
  }
}
Next