Nested If for a Three-way Choice

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

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

To make a three-way choice, a nested  if  is used. This is where an if-else statement is part of a the true-branch (or false-branch) of another if-else statement. So the nested if-else will execute only when the outer if-else has already made a choice between two branches. Here is a program fragment that makes a choice of one of the three suffixes.

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   )    // false-branch of first if
        suffix = "rd";                           // false-branch of first if
    else                                         // false-branch of first if
        suffix = "th";                           // false-branch of first if

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

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

  • when (count+1) is 2 the suffix "nd" is chosen;
  • when (count+1) is 3 the suffix "rd" is chosen;
  • when (count+1) is 4 or higher the suffix "th" is chosen.

QUESTION 9:

Fill in the two blanks so that the nested if's make the correct choice.