Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^172) | Selection and Encapsulation
false true
if ( Expression)
Statement 1
Statement 2
Figure 4.5 ifFlow of Control
Better yet, you could simply leave off the elsepart. The resulting statement is the ifform of
the ifstatement. Here is its syntax template:
Here’s an example of an ifform. Notice the indentation and the placement of the state-
ment that follows the if.
if (age < 18)
System.out.print("Not an eligible ");
System.out.println("voter.");
This statement means that if ageis less than 18, first print "Not an eligible "and then print
"voter."If ageis not less than 18, skip the first statement and go directly to printing "voter."
Figure 4.5 shows the flow of control for an ifform.
Like the two branches in an if-else, the one branch in an ifcan be a block. For example,
suppose you are writing an application to compute income taxes. One of the lines on the tax
form says, “Subtract line 23 from line 17 and enter the result on line 24; if the result is less
than zero, enter zero and check box 24A.” You can use an ifto perform this task in Java:
result = line17 – line23;
if (result < 0.0)
{
System.out.println("Check box 24A");
result = 0.0;
}
line24 = result;
If-Statement (the if form)
if ( Expression )
Statement

Free download pdf