Page 147 - Introduction to Programming with Java: A Problem Solving Approach
P. 147
Here’s a pseudocode description of the problem:
if temp 50 and 90 print “OK”
else
print “not OK”
Notice that the pseudocode condition uses and rather than and . The original problem specifica- tion says to print “OK” if the temperature is between 50 and 90 degrees. When people say “between,” they usually, but not always, mean to include the end points. Thus, we assumed that the 50 and 90 end points were supposed to be included in the OK range, and we chose to use and accord-
ingly. But in general, if you’re writing a program and you’re unsure about the end points for a particular range, you should not assume. Instead, you should ask the customer what he/she wants. The end points are important.
See Figure 4.5. It shows the Java implementation for the temperature-between-50-and-90 problem. In Java,ifbothoftwocriteriamustbemetforaconditiontobesatisfied(e.g.,temp >= 50andtemp <= 90), then separate the two criteria with the && operator. As indicated by Figure 4.5’s first callout, if both criteria use the same variable (e.g., temp), you must include the variable on both sides of the &&. Note the use of >= and <=. In pseudocode, it’s OK to use , , or even the words “greater than or equal to,” and “less than or equal to.” But in Java, you must use >= and <=.
Figure 4.5 Java implementation for the temperature-between-50-and-90 problem Operator Precedence
In Figure 4.5, note the parentheses around each of the two temperature comparisons. They force evaluation of the comparisons before evaluation of the &&. What would happen if we omitted those inner parentheses? To answer that sort of question, you need to refer to an operator precedence table. Appendix 2 provides a complete operator precedence table, but most of the cases you’ll encounter are covered by the abbreviated precedence table in Figure 4.6. All operators within a particular numbered group have equal precedence, but operators at the top of the figure (in groups 1, 2, . . .) have higher precedence than operators at the bot- tom of the figure (in groups . . . 7, 8).
Figure 4.6 shows that the comparison operators >= and <= have higher precedence than the logical op- erator &&. Thus, the >= and <= operations execute before the && operation—even if the inner parentheses in the condition in Figure 4.5 are omitted. In other words, we could have written Figure 4.5’s condition more simply, like this:
4.4 && Logical Operator 113
Think about where boundary values go.
temp must be repeated if ((temp >= 50)A&p& a(tgemop <P= D90F)) Enhancer
{
System.out.println("OK");
}
Use , not .
else
{
}
System.out.println("not OK");