Java Reference
In-Depth Information
sum += next;
if (sum < 0.0) {
negative = true;
}
}
System.out.println("sum = " + sum);
if (negative) {
System.out.println("Sum went negative");
} else {
System.out.println("Sum never went negative");
}
Boolean Zen
In 1974, Robert Pirsig started a cultural trend with his book Zen and the Art of
Motorcycle Maintenance: An Inquiry into Values. A slew of later books copied the
title with Zen and the Art of X, where X was Poker, Knitting, Writing, Foosball,
Guitar, Public School Teaching, Making a Living, Falling in Love, Quilting, Stand-up
Comedy, the SAT, Flower Arrangement, Fly Tying, Systems Analysis, Fatherhood,
Screenwriting, Diabetes Maintenance, Intimacy, Helping, Street Fighting, Murder,
and on and on. There was even a book called Zen and the Art of Anything.
We now join this cultural trend by discussing Zen and the art of type boolean . It
seems to take a while for many novices to get used to Boolean expressions. Novices
often write overly complex expressions involving boolean values because they don't
grasp the simplicity that is possible when you “get” how the boolean type works.
For example, suppose that you are writing a game-playing program that involves
two-digit numbers, each of which is composed of two different digits. In other words,
the program will use numbers like 42 that are composed of two distinct digits, but not
numbers like 6 (only one digit), 394 (more than two digits), or 22 (both digits are the
same). You might find yourself wanting to test whether a given number is legal for
use in the game. You can restrict yourself to two-digit numbers with a test like the
following one:
n >= 10 && n <= 99
You also have to test to make sure that the two digits aren't the same. You can get
the digits of a two-digit number with the expressions n / 10 and n % 10 . So you
can expand the test to ensure that the digits aren't the same:
n >= 10 && n <= 99 && (n / 10 != n % 10)
This test is a good example of a situation in which you could use a method to capture
a complex boolean expression. Returning a boolean will allow you to call the method
as many times as you want without having to copy this complex expression each time,
and you can give a name to this computation to make the program more readable.
 
Search WWH ::




Custom Search