Page 169 - Introduction to Programming with Java: A Problem Solving Approach
P. 169
In the NestedLoopRectangle program, there are two levels of nesting, but in general there may be any number of nesting levels. Each level adds another dimension to the problem. Our NestedLoopRectangle program is quite symmetrical. Both loops are the same type (they’re both for loops), and both loops do the same kind of thing (they both print something). In general, however, nested loops do not have to be the same type, and they do not have to do the same kinds of things.
4.13 boolean Variables
The conditions that appear in if statements and loops all evaluate to either true or false. We described these Boolean values in Section 4.2. Java also allows us to define a boolean variable, which is a variable that can hold a Boolean value. To declare a boolean variable, specify boolean for the variable’s type, like this:
boolean upDirection;
In this section, we describe when to use boolean variables in general, and we provide a program that uses boolean variables, including the upDirection variable shown above.
When to Use a boolean Variable
Programs often need to keep track of the state of some condition. You can use a boolean variable to keep
track of any two-way state—a yes/no, up/down, on/off attribute of some entity. For example, if you’re writ-
the state of the garage door’s direction—is the direction up or down? You need to keep track of the direction “state” because the direction determines what happens when the garage door opener’s button is pressed. If the direction state is up, then pressing the garage door button causes the direction to switch to down. If the direction state is down, then pressing the garage door button causes the direction to switch to up.
boolean variables are good at keeping track of the state of some condition when the state has one of two values. For example:
Garage Door Opener Example
The following code skeleton illustrates how the upDirection variable works: boolean upDirection = true;
4.13 boolean Variables 135
ing a program that simulates the operations of an electronic garage door opener, you’ll need to keep track of
Apago PDF Enhancer
Values for the state of a garage door opener’s direction
Comparable values for a boolean variable named upDirection
up
true
down
false
do
{
.. .
upDirection = !upDirection;
.. .
} while (<userpressesthegaragedooropenerbutton>);