Page 143 - Introduction to Programming with Java: A Problem Solving Approach
P. 143

                if statement. To emphasize the point that statements inside braces are logically inside something else, you should always indent statements that are inside braces. Since this is so important, we’ll say it again: Always indent when you’re inside braces!
When an if statement includes two or more subordinate statements, you must enclose the subordinate statements in braces. Said another way, you must use a block. A block, also called a compound statement, is a set of zero or more statements surrounded by braces. A block can be used anywhere a standard statement can be used. If you don’t use braces for the if statement’s two subordinate statements, the computer con- siders only the first statement to be subordinate to the if statement. When there is supposed to be just one subordinate statement, you’re not required to enclose it in braces, but we recommend that you do so anyway. That way, you won’t get into trouble if you come back later and want to insert additional subordinate state- ments at that point in your program.
Three Forms of the if Statement There are three basic forms for an if statement:
• “if”—usewhenyouwanttodoonethingornothing.
• “if,else”—usewhenyouwanttodoonethingoranotherthing. • “if, else if”—use when there are three or more possibilities.
Chapter 2 presented pseudocode versions of these forms. Figures 4.1, 4.2, and 4.3 show Java forms.
4.3 if Statement 109
 if (<condition>) <statement(s)>
Apago PDF Enhancer
   <if-condition> false
<following-statement>
true
<statement(s)>
    {
}
Figure 4.1 Syntax and semantics for the simple “if” form of the if statement
    <if-condition> false
<else-statement(s)>
<following-statement>
true
<statement(s)>
     {
if (<condition>) <if-statement(s)>
else
}
{
}
<else-statement(s)>
Figure 4.2 Syntax and semantics for the “if, else” form of the if statement






































































   141   142   143   144   145