The dangling-else problem:
The Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }).
if
( x >
5
) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" );
|
if
( x >
5
) if ( y > 5 ) System.out.println( "x and y are > 5" ); else System.out.println( "x is <= 5" );
|
Case I | Case II |
if
( x >
5
) { if ( y > 5 ) System.out.println( "x and y are > 5" ); } else System.out.println( "x is <= 5" );
|
Note that: Case I same as Case II. Case III is different from Case I & Case II. |
Case III |
Exercise 4.27 on page 152-153:
Determine the output for each the given sets of code when x is 9 and y is 11 and when x is 11 and y is 9.
Statements contained in a pair of braces form a block.
Example:
if ( grade >= 60 ) System.out.println("Passed"); else { System.out.println("Failed"); System.out.println("You must take this course again."); }
What happen if there is no braces?