next up previous contents
Next: Scope Up: 3 Iteration Previous: While loops   Contents

Flow control

There will be sometimes be points in the code inside the loop where it will be convenient to jump out of the loop completely, or skip the rest of the loop code and proceed directly to the next iteration. In Java, there are commands to do this. They are, respectively, break and continue. They allow finer control of the program flow, as the loop can be ended without waiting until the next time the test expression is evaluated. You should use these commands when it makes your code simpler or easier to understand. They are most useful when your programs become larger and more complex. The example below shows how they are used.

// generate random numbers and sum those that are <= 0.5, 
// until the running total exceeds 6.0.
double sum = 0;
while (true) // infinite loop, but break will be used to escape
{
    // get a new random number
    double r = math.random(); 

    // if r is outside the required range, skip ahead to the next iteration
    if (r > 0.5)
    {
        continue;
    }

    // do something with the random number
    sum = sum + r;
    System.out.println("random number " + r + " running total " + sum);

    // exit the loop when the running total exceeds the target
    if (sum > 6.0)
    {
        break; 
    }
}



RHUL Dept. of Physics