Java Reference
In-Depth Information
The if statement in Figure 3.3a is equivalent to the if statement in Figure 3.3b. In fact,
Figure  3.3b is the preferred coding style for multiple alternative if statements. This style,
called multi-way if-else statements , avoids deep indentation and makes the program easy
to read.
multi-way if statement
3.8
Suppose x = 3 and y = 2 ; show the output, if any, of the following code. What is
the output if x = 3 and y = 4 ? What is the output if x = 2 and y = 2 ? Draw a
flowchart of the code.
Check
Point
if (x > 2 ) {
if (y > 2 ) {
z = x + y;
System.out.println( "z is " + z);
}
}
else
System.out.println( "x is " + x);
3.9
Suppose x = 2 and y = 3 . Show the output, if any, of the following code. What is
the output if x = 3 and y = 2 ? What is the output if x = 3 and y = 3 ?
if (x > 2 )
if (y > 2 ) {
int z = x + y;
System.out.println( "z is " + z);
}
else
System.out.println( "x is " + x);
3.10
What is wrong in the following code?
if (score >= 60.0 )
System.out.println( "D" );
else if (score >= 70.0 )
System.out.println( "C" );
else if (score >= 80.0 )
System.out.println( "B" );
else if (score >= 90.0 )
System.out.println( "A" );
else
System.out.println( "F" );
3.6 Common Errors and Pitfalls
Forgetting necessary braces, ending an if statement in the wrong place, mistaking ==
for = , and dangling else clauses are common errors in selection statements.
Duplicated statements in if-else statements and testing equality of double values
are common pitfalls.
Key
Point
The following errors are common among new programmers.
Common Error 1: Forgetting Necessary Braces
The braces can be omitted if the block contains a single statement. However, forgetting the
braces when they are needed for grouping multiple statements is a common programming
error. If you modify the code by adding new statements in an if statement without braces,
you will have to insert the braces. For example, the following code in (a) is wrong. It should
be written with braces to group multiple statements, as shown in (b).
 
 
 
Search WWH ::




Custom Search