Java Reference
In-Depth Information
The first 50 prime numbers are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
This is a complex program for novice programmers. The key to developing a program-
matic solution for this problem, and for many other problems, is to break it into
subproblems and develop solutions for each of them in turn. Do not attempt to develop a
complete solution in the first trial. Instead, begin by writing the code to determine whether
a given number is prime, then expand the program to test whether other numbers are prime
in a loop.
To determine whether a number is prime, check whether it is divisible by a number
between
2
and
number/2
inclusive (lines 16-21). If so, it is not a prime number (line 18);
otherwise, it is a prime number. For a prime number, display it. If the count is divisible by
10
(lines 27-30), advance to a new line. The program ends when the count reaches
50
.
The program uses the
break
statement in line 19 to exit the
for
loop as soon as the num-
ber is found to be a nonprime. You can rewrite the loop (lines 16-21) without using the
break
statement, as follows:
subproblem
for
(
int
divisor =
2
;
divisor++) {
// If true, the number is not prime
if
(number % divisor ==
0
) {
// Set isPrime to false, if the number is not prime
isPrime =
false
;
divisor <= number /
2
&& isPrime;
}
}
However, using the
break
statement makes the program simpler and easier to read in this case.
You can use a confirmation dialog to prompt the user to confirm whether to continue
or exit a loop.
Key
Point
A sentinel-controlled loop can be implemented using a confirmation dialog. The answers
Ye s
or
No
continue or terminate the loop. The template of the loop may look as follows:
confirmation dialog
int
option = JOptionPane.YES_OPTION;
while
(option == JOptionPane.YES_OPTION) {
System.out.println(
"continue loop"
);
option = JOptionPane.showConfirmDialog(
null
,
"Continue?"
);
}
Listing 4.15 rewrites Listing 4.5, SentinelValue.java, using a confirmation dialog box. A
sample run is shown in Figure 4.4.
L
ISTING
4.15
SentinelValueUsingConfirmationDialog.java
1
import
javax.swing.JOptionPane;
2
3
public class
SentinelValueUsingConfirmationDialog {
4
public static void
main(String[] args) {
5
int
sum =
0
;