Fedora web server - 158 Control Structures: Part 1 Chapter 4 To
158 Control Structures: Part 1 Chapter 4 To force the preceding nested if structure to execute as it was originally intended, the structure must be written as follows: if ( x > 5 ) { if ( y > 5 ) System.out.println( “x and y are > 5″ ); } else System.out.println( “x is <= 5" ); The braces ({}) indicate to the compiler that the second ifstructure is in the body of the first if structure and that the else is matched with the first if structure. In Exercise 4.21 and Exercise 4.22, you will investigate the dangling-else problem further. The if selection structure normally expects only one statement in its body. To include several statements in the body of an if structure, enclose the statements in braces ({ and }). A set of statements contained within a pair of braces is called a block. Software Engineering Observation 4.2 A block can be placed anywhere in a program that a single statement can be placed. The following example includes a block in the else part of an if/else structure: if ( grade >= 60 ) System.out.println( “Passed” ); else { System.out.println( “Failed” ); System.out.println( “You must take this course again.” ); } In this case, if gradeis less than 60, the program executes both statements in the body of the else and prints Failed. You must take this course again. Notice the braces surrounding the two statements in the else clause. These braces are important. Without the braces, the statement System.out.println( “You must take this course again.” ); would be outside the body of the elsepart of the if structure and would execute regardless of whether the grade is less than 60. Common Programming Error 4.2 Forgetting one or both of the braces that delimit a block can lead to syntax or logic errors. Syntax errors (such as when one brace in a block is left out of the program) are caught by the compiler. A logic error (such as when both braces in a block are left out of the program) has its effect at execution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatal logic error allows a program to continue executing, but the program produces incorrect results. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01