This chapter introduces relational and logical operators. It also discusses the use of these operators to write Boolean expressions.
10. A Common Mistake
Answer:
// check that the weight is within range
if ( weight >= 136 && weight <= 147 )
System.out.println("In range!" );
else
System.out.println("Out of range." );
Another correct answer is:
// check that the weight is within range
if ( 136 <= weight && weight <= 147 )
System.out.println("In range!" );
else
System.out.println("Out of range." );
Here is another correct (but unclear) answer:
// check that the weight is within range
if ( weight < 148 && 135 < weight )
System.out.println("In range!" );
else
System.out.println("Out of range." );
There are more than a dozen correct answers. But the best answers are both correct and clear.
A Common Mistake
A Common Mistake
The boxer must weigh enough (weight >= 136),
and must also not weigh too much (weight <= 147).
The results of the two tests are combined with the and-operator, &&
.
A common mistake is to fail to use two separate comparisons. The following does not work:
if ( 136 <= weight <= 147 ) // wrong
The above is incorrect because 136 <= weight
forms a boolean subexpression. The second <=
would try to compare a boolean to an integer.
136 <= weight <= 147
-------------- ---
boolean <= 147
Here is a JavaScript version of the program:
|
Question 10:
Try the program with the weight 140.