Java Reference
In-Depth Information
31
String answer = JOptionPane.showInputDialog ( null ,
"Enter the sales amount\n(do not use commas or dollar signs)\n or click Cancel to
exit:" ) ;
32
33
if ( answer == null ) finish () ;
34
35
sales = Double .parseDouble ( answer ) ;
36
37
return sales;
38
}
39
40
//The finish() method ends the program.
41
public static void finish ()
42
{
43
System .exit ( 0 ) ;
44
}
45 }
FIGURE 4-13
The finish() method, displayed in lines 40 through 44, calls the System.exit()
method in line 43 to terminate the program. Note that the if statement in line 33
could call the System.exit() method directly, bypassing the need for the extra
finish() method. While that approach might work within the getSales() method,
coding the System.exit() method in the finish() method allows it to be called
from multiple methods, thus reducing code redundancy and keeping a single
exit for the program no matter which method calls it. Other uses for methods
such as finish() include opportunities to display a closing message, to save data,
or to perform memory clean-up tasks. Later in the chapter, after all data is vali-
dated and the commission rate has displayed to the user, an additional call to the
finish() method is added to the program.
The following steps enter an if statement to test the Cancel button.
To Code an if Statement to Test the Cancel Button
1. Enter lines 33 and 34 as shown in Figure 4-13.
The if statement will compare the variable, answer, to the null constant
(Figure 4-14). Line 34 is a blank line.
equal to
operator
if statement
null constant
FIGURE 4-14
(continued)
 
Search WWH ::




Custom Search