How the Three-way Choice Works

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

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

Answer:

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

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

How the Three-way Choice Works

The first if makes a choice between its true branch and its false branch. Its false branch is complicated, but that doesn't matter. Each branch of an if statement can be as complicated as needed. Here is the fragment again, with the first if's true branch in blue and its false branch in red:

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

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

For example, if (count+1) is equal to 2, the true branch is picked. The variable suffix gets "nd", and the false branch is completely skipped.

QUESTION 10:

The expression (count+1) is always greater than 1. For each of the following possible values of (count+1) which branch of the FIRST if will be executed?

    value of count+1which branch?
if ( count+1  == 2  )
  suffix = "nd";
else
  if ( count+1 == 3  )
    suffix = "rd";
  else
    suffix = "th";
2
3
4
5