(^170) | Selection and Encapsulation
What we really want to do is turn the elseclause into a sequenceof statements. This is easy.
Recall from Chapter 2 that the compiler treats the block (compound statement)
{
}
as a single statement. If you put a{}pair around the sequence of statements you want in a
branch of theifstatement, the sequence of statements becomes a single block. For example:
if (divisor != 0)
result = dividend / divisor;
else
{
System.out.println("Division by zero is not allowed.");
result = Integer.MAX_VALUE;
}
If the value ofdivisoris zero, the computer both displays the error message and sets the value
ofresulttoInteger.MAX_VALUEbefore continuing with whatever statement follows theifstatement.
Blocks can be used in both branches of an if-elsestatement. For example:
if (divisor != 0)
{
result = dividend / divisor;
System.out.println("Division performed.");
}
else
{
System.out.println("Division by zero is not allowed.");
result = Integer.MAX_VALUE;
}
When you use blocks in an ifstatement, you must remember a rule of Java syntax: Never use
a semicolon after the right brace of a block. Semicolons are used only to terminate simple state-
ments such as assignment statements and method calls. If you look at the earlier examples,
you won’t see a semicolon after the right brace that signals the end of each block.
The if Form
Sometimes you run into a situation where you want to say, “Ifa certain condition exists,
perform some action; otherwise, don’t do anything.” In other words, you want the computer
T
E
A
M
F
L
Y
Team-Fly®