Page 170 - Introduction to Programming with Java: A Problem Solving Approach
P. 170
136 Chapter 4 Control Statements
Theboolean upDirection = true;statementtellstheprogramtostartinthedown/closedposition and go up when the garage door opener is first pressed. Each iteration of the loop represents what happens
when the user presses the garage door opener button. The upDirection
ment implements the garage door opener’s toggling operation. If upDirection holds the value true, this statement changes it to false, and vice versa.
Now let’s look at the upDirection variable in the context of a complete GarageDoor program. In the program, each push of the Enter key on the computer keyboard simulates a push of the garage door opener button. The first push makes the door move upward. The second push makes the door stop. The third push makes the door move downward. The fourth push makes the door stop. And so forth, until the user enters ‘q’ to make the program quit. Note this client view for the GarageDoor program:
Sample session:
GARAGE DOOR OPENER SIMULATOR
Press Enter, or enter 'q' to
moving up
Press Enter, or enter 'q' to
stopped
Press Enter, or enter 'q' to
moving down
Press Enter, or enter 'q' to
stopped
quit:
quit:
quit:
quit:
Apago PDF Enhancer
Press Enter, or enter 'q' to quit: q
Figure 4.18 contains an implementation view of this program—the code. In the program, verify that up- Direction is used as previously discussed. Note that there’s a second boolean variable, inMotion. The upDirection boolean variable keeps track of the state of going up or down. That one state variable would be good enough if pressing a garage door opener button always generated an up or down motion. But as shown in the sample session, that’s not the case. Half the time, pressing the garage door opener causes the garage door to stop moving. Here’s the key point: If the door is moving, the door stops, and if the door is stopped, the door starts moving. We keep track of whether the garage door is currently moving with the help of a second state variable, inMotion. The inMotion state variable toggles (goes from false to true or vice versa) at each button push, whereas the upDirection state variable toggles only when the door is stopped—at every other button push.
Note how we use the inMotion and upDirection boolean variables by themselves as conditions for if statements:
if (inMotion)
{
if (upDirection)
{
.. .
In the past, you used relational operators within your conditions (e.g., ==, <=) But the only rule for a condi- tion is that it needs to evaluate to true or false. A boolean variable is either true or false, so using a boolean variable by itself for a condition is legal. Actually, using a boolean variable by itself for a
=
!upDirection state-