Page 118 - AP Computer Science A, 7th edition
P. 118

executed.
NESTED if STATEMENT
If the statement part of an if statement is itself an if statement, the result is a nested if statement.
Example 1
if (booleanexpr1) if (booleanexpr2)
statement; This is equivalent to
if (booleanexpr1 && booleanexpr2) statement;
Example 2
Beware the dangling else! Suppose you want to read in an integer and print it if it’s positive and even. Will the following code do the job?
int n = IO.readInt(); //read user input if (n > 0)
if (n % 2 == 0) System.out.println(n);
else
System.out.println(n + " is not positive");
A user enters 7 and is surprised to see the output
7 is not positive
The reason is that else always gets matched with the nearest unpaired if, not the first if as the indenting would suggest.
There are two ways to fix the preceding code. The first is to use {} delimiters to group the statements correctly.


















































































   116   117   118   119   120