Java Reference
In-Depth Information
LISTING 5.4
continued
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
}
A block statement is a collection of statements enclosed in braces. We've used these
braces many times in previous examples to enclose method and class definitions.
The program called Guessing , shown in Listing 5.5, uses an if-else statement
in which the statement of the else clause is a block statement.
If the guess entered by the user equals the randomly chosen answer, an appro-
priate acknowledgment is printed. However, if the answer is incorrect, two state-
ments are printed, one that states that the guess is wrong and one that prints the
actual answer. A programming project at the end of this chapter expands the
concept of this example into the Hi-Lo game.
Note that if the block braces were not used, the sentence stating that the
answer is incorrect would be printed if the answer was wrong, but the sentence
revealing the correct answer would be printed in all cases. That is, only the first
statement would be considered part of the else clause.
Remember that indentation means nothing except to the human reader. Statements
that are not blocked properly can lead to the programmer making improper assump-
tions about how the code will execute. For example, the following code is misleading:
if (depth >= UPPER_LIMIT)
delta = 100;
else
System.out.println ("WARNING: Delta is being reset to ZERO");
delta = 0; // not part of the else clause!
The indentation (not to mention the logic of the code) implies that the variable
delta is reset to zero only when depth is less than UPPER_LIMIT . However,
without using a block, the assignment statement that resets delta to zero is not
governed by the if-else statement at all. It is executed in either case, which is
clearly not what is intended.
VideoNote
Examples using
conditionals.
 
Search WWH ::




Custom Search