if
Statements with RangesThe "Charge Card Statement" problem of lab 3.1 asks you to design a program that prints one of three different statements depending on the value of a number.
You will need to use three if
statements, one for each case. One
way to do this is for some of those statements to use a compound boolean condition
(see pp. 120-2 of your textbook for a review of these). For example, let's say
I wanted to test if a number, x, was between 80 and 120:
int x; ... if (x > 80 && x < 120) System.out.println("x is greater than 80 and less than 120.");You can solve your problem using this technique, but you should be careful about the values you use in the conditional. For example, let's say you wanted to print out one message if our variable, x, was between 80 and 120, and another if it was less. You might try:
int x; ... if (x < 80) System.out.println("x is less"); if (x > 80 && x < 120) System.out.println("x is between 80 and 120");
Now, here, I've used intentionally vague language. The word, "between" in English
is ambiguous. When I say "x is between 4 and 6", am I saying x can be 4, 5,
or 6? Or am I saying that x is 5? If we want to be more precise in our speaking,
we can use expressions such as, "x is between 4 and 6, inclusively," or, even
better, "x is a number greater than or equal to 4 and less than or equal to
6." The code above is faulty because it does not deal with the situation in
which x is exactly 80. When dealing with ranges of numbers like this,
we usually want to use the inequality operators <=
and >=
to be precise. So we might change the code above to be:
int x; ... if (x <= 80) System.out.println("x is 80 or less"); if (x > 80 && x < 120) System.out.println("x is between 80 and 120");
Now, someone might want to avoid the use of the inequality operators by being more careful about the numbers in the conditional clauses:
int x; ... if (x < 81) // NOTE THE CHANGE HERE!!!! System.out.println("x is 80 or less"); if (x > 80 && x < 120) System.out.println("x is between 80 and 120");
Technically this is okay, but it sure looks clunky. The (x <= 80)
clause says much more clearly what you are trying to do. Plus, if x was a double,
rather than an int, the above code wouldn't suffice at all.
For a third, slightly less verbose approach to solving these kinds of problems, see my page on "else if" statements.