Java Reference
In-Depth Information
Try It Out - Calculating Primes III
Suppose we want our Primes program to generate a given number of primes, rather than check up to a
given integer value. In this case we don't know how many numbers we need to check to generate the
required number of primes. This is a case where an indefinite loop is useful. We can code this as follows:
public class FindPrimes {
public static void main(String[] args) {
int nPrimes = 50; // The maximum number of primes required
OuterLoop:
for(int i = 2; ; i++) { // This loop runs forever
// 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
if(--nPrimes == 0) { // Decrement the prime count
break; // It is zero so we have them all
}
}
}
}
How It Works
This program is very similar to the previous version. The principal differences are that nPrimes
contains the number of primes required, so the program will produce the first 50 primes, instead of
finding the primes between 2 and 50. The outer loop, controlled by i , has the loop condition omitted,
so the loop has no direct mechanism for ending it. The loop must be terminated by the code within the
loop, otherwise it will continue to execute indefinitely.
Here the termination of the outer loop is controlled by the if statement following the output statement.
As we find each prime, the value is displayed, after which the value of nPrimes is decremented in the
if statement:
if(--nPrimes == 0) { // Decrement the prime count
break; // It is zero so we have them all
}
The break statement will be executed when nPrimes has been decremented to zero, and this will exit
the outer loop.
The Labeled break Statement
Java also makes a labeled break statement available to you. This enables you to jump immediately to
the statement following the end of any enclosing statement block or loop that is identified by the label
in the labeled break statement. This mechanism is illustrated in the following diagram:
Search WWH ::




Custom Search