Java Reference
In-Depth Information
Testing the while Statement
The following steps compile and test the while statement.
To Compile and Test the while Statement
1. With the Data Disk in drive A, compile the program by clicking Compile
Java on the Tools menu. If TextPad notifies you of errors, click
Commission.java in the Selector window, fix the errors, and then
compile again. When the program compiles with no errors, click Run
Java Application on the Tools menu.
2. When the program displays the Input dialog box, type -35000 and then
click the OK button.
3. When the program displays the Error dialog box, click the OK button.
4. When the program again displays the Input dialog box, type 35000 and
then click the OK button. Click the Close button in the command
prompt window title bar.
The program displays an error message when a negative number is entered.
The program accepts the positive value as valid input data.
Run the program several more times and test valid and invalid entries for
sales amounts, such as zero or alphanumeric data.
The getCode() Method
The next step after obtaining a valid sales amount is to request a commission
code. The method to accept a valid commission code from the user employs
similar logical constructs as the getSales() method. Figure 4-24 displays the line
of code to call the getCode() method (line 23) and the getCode() method defini-
tion (lines 53 through 80).
In the getCode() method, line 58 declares the variable, code, and assigns an
initial value of 0. Line 59 declares a boolean variable, done, and assigns an initial
value of false. Execution then enters the while statement in lines 62 through 78,
which repeats until a valid code is entered. The try and catch statements in lines
64 through 77 handle any exceptions by displaying an error message if the user
enters an invalid commission code. Note that it is acceptable to reuse the variable
name, done, in line 59 because each occurrence is local in scope — that is, the
occurrence of the variable, done, is unique to the method in which it is used.
Search WWH ::




Custom Search