Java Reference
In-Depth Information
A block statement can be used anywhere a single statement is called for in Java
syntax. For example, the if portion of an if-else statement could be a block, or
the else portion could be a block (as we saw in the Guessing program), or both
parts could be block statements. For example:
if (boxes != warehouse.getCount())
{
System.out.println ("Inventory and warehouse do NOT match.");
System.out.println ("Beginning inventory process again!");
boxes = 0;
}
else
{
System.out.println ("Inventory and warehouse MATCH.");
warehouse.ship();
}
In this if-else statement, the value of boxes is compared to a value obtained by
calling the getCount method of the warehouse object (whatever that is). If they
do not match exactly, two println statements and an assignment statement are
executed. If they do match, a different message is printed and the ship method of
warehouse is invoked.
Nested if Statements
The statement executed as the result of an if statement could be another if state-
ment. This situation is called a nested if . It allows us to make another decision
after determining the results of a previous decision. The program in Listing 5.6,
called MinOfThree , uses nested if statements to determine the smallest of three
integer values entered by the user.
Carefully trace the logic of the MinOfThree program, using various input sets with
the minimum value in all three positions, to see how it determines the lowest value.
An important situation arises with nested if statements. It may seem that an
else clause after a nested if could apply to either if statement. For example:
if (code == 'R')
if (height <= 20)
System.out.println ("Situation Normal");
else
System.out.println ("Bravo!");
 
Search WWH ::




Custom Search