Java Reference
In-Depth Information
Using boolean variables adds to the readability of your programs because it
allows you to give names to tests. Consider the kind of code you would generate for a
dating program. You might have some integer variables that describe certain attri-
butes of a person: looks , to store a rough estimate of physical beauty (on a scale of
1-10); IQ , to store intelligence quotient; income , to store gross annual income; and
snothers , to track intimate friends (“snother” is short for “significant other”). Given
these variables to specify a person's attributes, you can develop various tests of suit-
ability. As you are writing the program, you can use boolean variables to give names
to those tests, adding greatly to the readability of the code:
boolean cute = (looks >= 9);
boolean smart = (IQ > 125);
boolean rich = (income > 100000);
boolean available = (snothers == 0);
boolean awesome = cute && smart && rich && available;
You might find occasion to use a special kind of boolean variable called a flag.
Typically we use flags within loops to record error conditions or to signal completion.
Different flags test different conditions. As an analogy, consider a referee at a sports
game who watches for a particular illegal action and throws a flag if it happens. You
sometimes hear an announcer saying, “There is a flag down on the play.”
Let's introduce a flag into the cumulative sum code we saw in the previous chapter:
double sum = 0.0;
for (int i = 1; i <= totalNumber; i++) {
System.out.print(" #" + i + "? ");
double next = console.nextDouble();
sum += next;
}
System.out.println("sum = " + sum);
Suppose we want to know whether the sum ever goes negative at any point. Notice
that this situation isn't the same as the situation in which the sum ends up being neg-
ative. Like a bank account balance, the sum might switch back and forth between
positive and negative. As you make a series of deposits and withdrawals, the bank
will keep track of whether you overdraw your account along the way. Using a
boolean flag, we can modify the preceding loop to keep track of whether the sum
ever goes negative and report the result after the loop:
double sum = 0.0;
boolean negative = false;
for (int i = 1; i <= totalNumber; i++) {
System.out.print(" #" + i + "? ");
double next = console.nextDouble();
Search WWH ::




Custom Search