Java Reference
In-Depth Information
if(a != 0 )
if(a > 1)
System.out.println("x is positive and non-zero");
else
System.out.println("x is zero or negative");
Intheprecedingcodefragment,thepathofexecutionisdifferentifthe
elseclauseispairedwiththeinnerifstatement,orwiththeouterone.
ThegeneralruleusedbyJavainsolvingthedanglingelseproblemisthat
eachelsestatementispairedwiththeclosestifstatementthatdoesnot
haveanelse,andthatislocatedinthesameblock.Indentationinthepre-
cedingcodefragmenthelpsyouseethattheelsestatementislinkedto
theinnerif.
Youcanuserosterstoforceadifferentassociationbetweenifandelse
statements,forexample
if(a != 0 )
{
if(a > 1)
System.out.println("x is positive and non-zero");
}
else
System.out.println("x must be zero");
Intheprecedingcodefragmenttheclosestifstatementwithoutan
else,andlocatedinthesameblock,isthestatement
if(a!=0)
Programmersnote:
Anelsestatementispairedwiththeclosestifwithoutanelselocated
inthesameblock.
Else-if clause
Youhaveseenhowthedanglingelseproblemcancauseunpredictedasso-
ciationsofanelseclausewithanifstatement.Therelationshipbetween
twoconsecutiveifstatementscanalsocauseproblems.Theflowchartin
Figure9-1 showsthecaseofacascadedifconstruct,inwhichasecondif
statement is conditioned to the first one being true. However, if the second
if statement is not nested in the first one, then its evaluation is independent
of the result of the first if. The following code shows this case.
if(userInput == 1 || userInput == 2)
System.out.println(“BEEP-BEEP”);
if(userInput == 2)
System.out.println(“Input = 2");
Search WWH ::




Custom Search