Java Reference
In-Depth Information
}
Primes3.java
This program outputs the first 50 primes.
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 produces the first 50 primes, instead of finding the primes
between 2 and 50, and the for 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 continues to execute indefinitely.
Here the termination of the outer loop is controlled by the if statement following the output statement.
As you 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 is executed when nPrimes has been decremented to zero, and this exits the outer
loop.
The Labeled break Statement
Java also has a labeled break statement. 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.
The label precedes the opening brace of the block that it identifies. Figure 3-7 illustrates how the labeled
break statement works.
FIGURE 3-7
 
 
Search WWH ::




Custom Search