Java Reference
In-Depth Information
The checking is done in the if statement in the inner loop. If j divides i exactly i%j will be 0, so
isPrime will be set to false . In this case the break will be executed to exit the inner loop - there is
no point in continuing as we now know that the value being tested is not prime. The next statement to
be executed will be the if statement after the closing brace of the inner loop block. You can also reach
this point by a normal exit from the loop which occurs when the value is prime, so it is necessary to
check the value of isPrime to see whether we do have a prime or not.
This example could be simplified if we used the labeled continue instead of the break statement:
Try It Out - Calculating Primes II
Try the following changes to the code in the Primes class.
public class Primes {
public static void main(String[] args) {
int nValues = 50; // The maximum value to be checked
// Check all values from 2 to nValues
OuterLoop:
for(int i = 2; i <= nValues; i++) {
// Try dividing by all integers from 2 to i-1
for(int j = 2; j < i; j++) {
if(i%j == 0) { // This is true if j divides exactly
continue OuterLoop; // so exit the loop
}
}
// We only get here if we have a prime
System.out.println(i); // so output the value
}
}
}
How It Works
We no longer need the isPrime variable to indicate whether we have a prime or not, as we can only
reach the output statement through a normal exit from the inner loop. When this occurs it means we
have a prime. If we get an exact divisor, implying the current value of i is not prime, the labeled
continue transfers immediately to the next iteration of the outer loop. The output from this version of
the program is the same as before.
Breaking Indefinite Loops
You will find that sometimes you will need to use a loop where you don't know in advance how many
iterations are required. This can arise when you are processing external data items that you might be
reading in from the keyboard for example, and you do not know in advance how many there are. You
can often use a while loop in these circumstances with the loop condition determining when the loop
should end, but sometimes it can be convenient to use an indefinite loop instead, with a break
statement to end the loop.
Search WWH ::




Custom Search