26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 Control Structures: Part 1 157<br />

If studentGrade is greater than or equal <strong>to</strong> 90, the first four conditions will be true, but<br />

only the System.out.println statement after the first test will be executed. After that<br />

particular System.out.println is executed, the else part of the “outer” if/else<br />

statement is skipped.<br />

Good <strong>Program</strong>ming Practice 4.4<br />

If there are several levels of indentation, each level should be indented by the same additional<br />

amount of space. 4.4<br />

Most <strong>Java</strong> programmers prefer <strong>to</strong> write the preceding if structure as<br />

if ( grade >= 90 )<br />

System.out.println( "A" );<br />

else if ( grade >= 80 )<br />

System.out.println( "B" );<br />

else if ( grade >= 70 )<br />

System.out.println( "C" );<br />

else if ( grade >= 60 )<br />

System.out.println( "D" );<br />

else<br />

System.out.println( "F" );<br />

Both forms are equivalent. The latter form is popular because it avoids the deep indentation<br />

of the code <strong>to</strong> the right. Such deep indentation often leaves little room on a line, forcing<br />

lines <strong>to</strong> be split and decreasing program readability.<br />

It is important <strong>to</strong> note that the <strong>Java</strong> compiler always associates an else with the previous<br />

if unless <strong>to</strong>ld <strong>to</strong> do otherwise by the placement of braces ({}). This attribute is<br />

referred <strong>to</strong> as the dangling-else problem. For example,<br />

if ( x > 5 )<br />

if ( y > 5 )<br />

System.out.println( "x and y are > 5" );<br />

else<br />

System.out.println( "x is 5" is output. Otherwise, it appears<br />

that if x is not greater than 5, the else part of the if/else structure outputs the string<br />

"x is 5" );<br />

else<br />

System.out.println( "x is 5"—is displayed. <strong>How</strong>ever,<br />

if the second condition is false, the string "x is

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!