Java Reference
In-Depth Information
15 if ( age > 21 )
16 {
17
if ( age > 64 )
18
{
19
seniorCount = seniorCount + 1;
20
System .out.println ( "Senior" ) ;
}
21
22
else
23
{
24
adultCount = adultCount + 1;
25
System .out.println ( "Adult" ) ;
26
}
27
}
28
else
29
{
30
if ( age > 12 ) System .out.println ( "Teen" ) ;
3 32 }
else System .out.println ( "Youth" ) ;
FIGURE 4-12
Lines 30 and 31 are nested within the else clause that begins in line 28; how-
ever, because there is only one clause for each of the if and else clauses in lines 30
and 31, no braces are necessary, and the clauses are coded on one line. Program-
mers normally indent nested structures to facilitate easy reading. TextPad will
indent automatically after you type a brace.
When programming selection structures, be careful to use two equal signs
(= =) in the condition. Beginning programmers sometimes use only one equal
sign (=), forgetting that the condition must be boolean, which requires two
equal signs (= =) for equality. Using only one equal sign (=) results in a compile
error. Another common error is forgetting the braces for a block if or else state-
ment. In those cases, Java considers only the first line as part of the condition,
incorrectly executing all of the other lines.
Using Operators in an if…else Statement
In many instances, a decision to execute one set of code or another is based
on the evaluation of one or more conditions. In Chapter 3, you learned that
different types of comparison operators are used in conditional expressions to
evaluate the relationship between two expressions or values logically. Relational
operators are used to compare the relation of two values; equality operators are
used to determine if two values are equal. The values may be variables, constants,
numbers, strings, or the result of a function or method.
Another type of operator, the logical operator , is used to connect two
conditional expressions. As shown in Table 4-5 on the next page, the logical AND
operato r (&&) connects two expressions, x and y, so that both conditions indi-
vidually must be evaluated as true for the entire expression, x && y, to be evalu-
ated as true. The logical OR operator (| |) connects two expressions, x and y, so
that the whole expression, x | | y, evaluates to true if either x or y evaluates to
true, or if they both do. The logical NOT operator (!) connects two expressions,
x and y, so that if x evaluates to true, then the expression !x evaluates to false,
and vice versa.
Search WWH ::




Custom Search