Boolean Variables- BOO! scared you

Do  if statements make you nervous?
Do you slow to a crawl when you read a condition? Wouldn’t it be
nice if you could glance at a condition and make sense of it very quickly?
To some extent, you can. If you’re willing to create some additional variables,
you can make your code easier to read.

public static void main(String args[]) {
Scanner myScanner = new Scanner(System.in);
int age;
double price = 0.00;
char reply;
boolean isKid, isSenior, hasCoupon, hasNoCoupon;
System.out.print(“How old are you? “);
age = myScanner.nextInt();
System.out.print(“Have a coupon? (Y/N) “);
reply = myScanner.findInLine(“.”).charAt(0);
isKid = age < 12;
isSenior = age >= 65;
hasCoupon = reply == ‘Y’ || reply == ‘y’;
hasNoCoupon = reply == ‘N’ || reply == ‘n’;
(continued)
Chapter 10: Which Way Did He Go? 165
Listing 10-3 (continued)
if (!isKid && !isSenior) {
price = 9.25;
}
if (isKid || isSenior) {
price = 5.25;
}
if (hasCoupon) {
price -= 2.00;
}
if (!hasCoupon && !hasNoCoupon) {
System.out.println(“Huh?”);
}
System.out.print(“Please pay $”);
System.out.print(price);
System.out.print(“. “);
System.out.println(“Enjoy the show!”);
}
}
By the time you encounter the two if statements,
the conditions can use simple words — words like isKid, isSenior, and
hasCoupon. With all these boolean variables, expressing each if statement’s
condition is a snap. Adding a boolean variable can make your code more manageable. But some
programming languages don’t have boolean variables, so many programmers
prefer to create if conditions on the fly. That’s why learning a  combination of the two techniques
is best.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s