Search

Friday, December 21, 2018

The if/else Selection Structure

The if selection structure performs an indicated action only when the given condition evaluates to true; otherwise, the action is skipped. The if/else selection structure allows the programmer to specify that a different action is to be performed when the condition is true rather than when the condition is false. For example, the pseudo-code statement If student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” prints Passed if the student’s grade is greater than or equal to 60 and prints Failed if the student’s grade is less than 60. In either case, after printing occurs, the next pseudo-code statement in sequence is “performed.” Note that the body of the else is also indented.
The indentation convention you choose should be carefully applied throughout your programs. It is difficult to read programs that do not use uniform spacing conventions. The preceding pseudo-code If/else structure may be written in Java as

if ( studentGrade >= 60 )    
System.out.println( "Passed" ); 
else   System.out.println( "Failed" ); 

The flowchart nicely illustrates the flow of control in an if/else structure. Once again, note that, besides small circles and arrows, the only symbols in the flowchart are rectangles (for actions) and a diamond (for a decision). We continue to emphasize this action/decision model of computing. Imagine again a deep bin containing as many empty double-selection structures as might be needed to build a Java algorithm. The programmer’s job is to assemble the selection structures (by stacking and nesting) with other control structures required by the algorithm and to fill in the empty rectangles and empty diamonds with actions and decisions appropriate to the algorithm being implemented. 
The conditional operator (?:) is related to the if/else structure. ?: is Java’s only ternary operator—it takes three operands. The operands together with ?: form a conditional expression. The first operand is a Boolean expression, the second is the value for the conditional expression if the condition evaluates to true and the third is the value for the conditional expression if the condition evaluates to false. For example, the statement

System.out.println( studentGrade >= 60 ? "Passed" : "Failed" ); 

contains a conditional expression that evaluates to the string "Passed" if the condition studentGrade>=60 is true and to the string "Failed" if the condition is false. Thus, this statement with the conditional operator performs essentially the same function as the if/else statement given previously. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses. We will see that conditional operators can be used in some situations where if/else statements cannot. 
Nested if/else structures test for multiple cases by placing if/else structures inside if/else structures. For example, the following pseudo-code statement prints A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades: If student’s grade is greater than or equal to 90 Print “A” else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F” This pseudo-code may be written in Java as

if ( studentGrade >= 90 )   
System.out.println( "A" ); 
else if ( studentGrade >= 80 )      
System.out.println( "B" ); 
else      
if ( studentGrade >= 70 )         
System.out.println( "C" );      
else
         if ( studentGrade >= 60 )            
System.out.println( "D" );         
else
System.out.println( "F" );

If student Grade is greater than or equal to 90, the first four conditions will be true, but only the System.out.println statement after the first test will be executed. After that particular System.out.println is executed, the else part of the “outer” if/else statement is skipped.

Most Java programmers prefer to write the preceding if structure as 

if ( grade >= 90 )   
System.out.println( "A" ); 
else 
if ( grade >= 80 )   
System.out.println( "B" ); 
else if ( grade >= 70 )   
System.out.println( "C" ); 
else
 if ( grade >= 60 )   
System.out.println( "D" ); 
else   
System.out.println( "F" );

Both forms are equivalent. The latter form is popular because it avoids the deep indentation of the code to the right. Such deep indentation often leaves little room on a line, forcing lines to be split and decreasing program readability. It is important to note that the Java compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). This attribute is referred to as the dangling-else problem. For example,

if ( x > 5 ) if ( y > 5 )      
System.out.println( "x and y are > 5" ); 
else   
System.out.println( "x is <= 5" ); 

appears to indicate that if x is greater than 5, the if structure in its body determines if y is also greater than 5. If so, the string "x and y are > 5" is output. Otherwise, it appears that if x is not greater than 5, the else part of the if/else structure outputs the string "x is <= 5". Beware! The preceding nested if structure does not execute as it would appear to. The compiler actually interprets the preceding structure as 

if ( x > 5 ) if ( y > 5 )      
System.out.println( "x and y are > 5" ); 
else      
System.out.println( "x is <= 5" );

in which the body of the first if structure is an if/else structure. This structure tests if x is greater than 5. If so, execution continues by testing if y is also greater than 5. If the second condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second condition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5.

To force the preceding nested if structure to execute as it was originally intended, the structure must be written as follows:

if ( x > 5 ) 
{
 if ( y > 5 )      
System.out.println( "x and y are > 5" ); 
}
 else   
System.out.println( "x is <= 5" );

The braces ({}) indicate to the compiler that the second if structure is in the body of the first if structure and that the else is matched with the first if structure. In Exercise 4.21 and Exercise 4.22, you will investigate the dangling-else problem further. The if selection structure normally expects only one statement in its body. To include several statements in the body of an if structure, enclose the statements in braces ({ and }). A set of statements contained within a pair of braces is called a block. 

The following example includes a block in the else part of an if/else structure:

if ( grade >= 60 )   
System.out.println( "Passed" ); 
else 
{
System.out.println( "Failed" );   
System.out.println( "You must take this course again." ); 
}

In this case, if grade is less than 60, the program executes both statements in the body of the else and prints
Failed. You must take this course again.
Notice the braces surrounding the two statements in the else clause. These braces are important. Without the braces, the statement

System.out.println( "You must take this course again." );

would be outside the body of the else part of the if structure and would execute regardless of whether the grade is less than 60.

0 comments:

Post a Comment