Java Reference
In-Depth Information
6
7 // Keep reading data until the user answers No
8 int option = JOptionPane.YES_OPTION;
9 while (option == JOptionPane.YES_OPTION) {
10 // Read the next data
11 String dataString = JOptionPane.showInputDialog(
12
confirmation option
check option
input dialog
"Enter an integer: " );
13
int data = Integer.parseInt(dataString);
14
15 sum += data;
16
17 option = JOptionPane.showConfirmDialog( null , "Continue?" );
18 }
19
20 JOptionPane.showMessageDialog( null , "The sum is " + sum);
21 }
22 }
confirmation dialog
message dialog
(a)
(b)
(c)
(d)
(e)
F IGURE 4.4
The user enters 3 in (a), clicks Yes in (b), enters 5 in (c), clicks No in (d), and the result is shown in (e).
The program displays an input dialog to prompt the user to enter an integer (line 11) and
adds it to sum (line 15). Line 17 displays a confirmation dialog to let the user decide whether
to continue the input. If the user clicks Yes, the loop continues; otherwise, the loop exits.
Finally, the program displays the result in a message dialog box (line 20).
The showConfirmDialog method (line 17) returns an integer JOptionPane.YES_OPTION ,
JOptionPane.NO_OPTION , or JOptionPane.CANCEL_OPTION , if the user clicks Ye s ,
No , or Cancel . The return value is assigned to the variable option (line 17). If this value is
JOptionPane.YES_OPTION , the loop continues (line 9).
K EY T ERMS
loop body 134
nested loop 152
off-by-one error
break statement 159
continue statement
159
136
do-while loop
144
output redirection
143
for loop 147
infinite loop 136
input redirection
posttest loop
150
pretest loop
150
143
sentinel value
141
iteration
134
while loop
134
loop
134
 
 
Search WWH ::




Custom Search