Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^166) | Selection and Encapsulation
PEANUTS reprinted by permission of United Features Syndicate, Inc.
One final comment about parentheses: Java, like other programming languages, re-
quires that you always use parentheses in pairs. Whenever you write a complicated ex-
pression, take a minute to go through and pair up all of the opening parentheses with their
closing counterparts.


Changing English Statements into Logical Expressions


In most cases, you can write a logical expression directly from an English statement or mathe-
matical term in an algorithm. But you have to watch out for some tricky situations. Recall our
example logical expression:
midtermGrade == 'A'|| finalGrade == 'A'
In English, you would be tempted to write this expression: “Midterm grade or final grade equals
A.” In Java, you can’t write the expression as you would in English. That is,
midtermGrade || finalGrade == 'A'
won’t work because the ||operator connects a charvalue (midtermGrade) and a logical
expression (finalGrade == 'A'). The two operands of ||must both be logical expressions. This
example will generate a syntax error message.
A variation of this mistake is to express the English assertion “iequals either 3 or 4” as
i == 3 || 4
This syntax is incorrect. In the second subexpression, 4 is an intrather than a booleanvalue.
The ||operator (and the &&operator) can only connect two booleanexpressions. Here’s what
we want:
i == 3 || i == 4
In math books, you might see notation like this:
12 < y< 24
It means “yis between 12 and 24.” This expression is illegal in Java. First, the relation 12 < yis
evaluated, giving a booleanresult. Next, the computer tries to compare it with the number 24.
Because a booleanvalue cannot be converted to any type other than String, the expression is
invalid. To write this expression correctly in Java, you must use the &&operator:
12 < y && y < 24
Free download pdf