Java Reference
In-Depth Information
Line 30 declares a boolean variable, done, and assigns it a value of false, thus
allowing the program to enter the loop structure that begins with the while
statement in line 33. The exclamation point is the logical NOT operator, thus
causing the code in the while statement to loop when the value of done is not
true. Recall that boolean variables may be used as conditions. In this example,
the variable serves as a flag to notify the loop whether or not to execute. The
braces for the while statement in lines 34 and 49 enclose the code that should
repeat until the value of done is true.
Within the body of the while loop, some trigger must cause the loop to
stop — in other words, something must happen within the code that changes
the state of the boolean variable, done. In line 43, an else clause has been added
to the selection structure. The else clause is executed if the entered sales amount
did not throw an exception automatically when the sales amount was parsed in
line 41, and was not greater than zero in line 42. When execution passes back to
line 33, the true value will cause the loop created by the while statement to stop
executing. Control then will pass to line 50, outside the while statement.
The following step adds the code for the while loop to the getSales()
method.
To Enter Code for the while Statement
1. Within the getSales() method in the Commission program, enter new
lines 30 through 34, line 43, and line 49 as shown in Figure 4-22. Use
appropriate spacing and indentation.
The new code is displayed (Figure 4-23). Your lines may wrap differently.
assigns boolean
variable, done,
value of false
new code
else statement
closing brace
for while loop
while
statement
FIGURE 4-23
 
Search WWH ::




Custom Search