Java Reference
In-Depth Information
Table 4-8
The while Statement
General form:
while(condition)
{
. . . lines of code to repeat while above condition is true;
}
Purpose:
To create a process that will repeat, or loop through, executing a series of statements while
the condition in the while statement is true. The word, while , is a reserved keyword. The
condition must be a boolean expression that evaluates to true or false. The code repeats as
long as the condition is evaluated as true. The condition eventually must evaluate to false in
order to exit the loop.
Example:
while(!done)
{
System.out.println("Are you done (yes or no)");
String answer = dataIn.readLine();
if (answer == "yes") done;
}
The getSales() method requires that its statements continue to be executed
while the sales amount data entered by the user is invalid. If the program throws
an exception, it should loop back to the JOptionPane input dialog box and
allow the user to enter a new sales amount. Figure 4-22 displays the complete
getSales() method definition. Lines 30 through 34, line 43, and line 49 are new to
the method.
25
//The getSales() method asks the user to input a dollar amount and validates it.
26
public static double getSales ()
27
{
28
//declare method variables
29
double sales = 0.0;
30
boolean done = false ;
31
32
//loop while not done
33
while ( !done )
34
{
35
String answer = JOptionPane.showInputDialog ( null ,
"Enter the sales amount\n(do not use commas or dollar signs)\n or click Cancel
to exit:" ) ;
36
37
if ( answer == null ) finish () ;
38
39
try
40
{
41
sales = Double .parseDouble ( answer ) ;
42
if ( sales <= 0 ) throw new NumberFormatException () ;
43
else done = true ;
44
}
45
catch ( NumberFormatException e )
46
{
47
JOptionPane.showMessageDialog ( null ,
"Your entry was not in the proper format." , "Error" ,
INFORMATION_MESSAGE ) ;
JOptionPane.
48
}
49
}
50
return sales;
51
}
FIGURE 4-22
 
Search WWH ::




Custom Search