go to previous page   go to home page   go to next page hear noise

Can a single if-else statement choose one of three options?

Answer:

No. An if-else statement makes a choice between two options.


Nested If for a Three-way Choice

String suffix;

int count=0;    // count is the number of integers added so far.
                // count+1 is the next integer to read

 . . . . 

if ( count+1    )
    suffix = "nd";
else
    if ( count+1   )
        suffix = "rd";         
    else              
        suffix = "th";        

System.out.println( "Enter the " + 
    (count+1) + suffix + " integer (enter 0 to quit):" );

To make a three-way choice, use a nested  if  by writing an if statement as a branch of an outer if statement.

The nested if executes only when the outer if has already made a choice between two branches. Look at the above program fragment.

The false-branch of the first if statement consists of another entire if statement. Fill in the blanks so that:


QUESTION 9:

Fill in the two blanks so that the nested if makes the correct choice.