Three-way Decisions

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   hear noise   go to next page

Answer:

Enter the price:
100
Item cost: 100 Tax: 5.0 Total: 105.0

Three-way Decisions

You might wonder about the restriction that an if statement makes only a two-way decision. Surely you must sometimes pick from more than just two branches?

We ran into this problem with a previous example program that divided integers into negative and non-negative. It really should pick one of three choices:

  • Negative: ... -3 -2 -1
  • Zero: 0
  • Positive: +1 +2 +3 ...

Two-way decisions can do this. First divide the integers into two groups (using a two-way decision):

  • Negative: ... -3 -2 -1
  • Zero and Positive: 0 +1 +2 +3 ...

Then further further divide the second group (by using another two-way decision):

  • Negative: ... -3 -2 -1
  • Zero and Positive:
    • Zero: 0
    • Positive: +1 +2 +3 ...

By repeatedly splitting groups into subgroups, you can split a collection into any number of fine divisions.

QUESTION 16:

How could you divide a group of people into:

  • children
  • male adults
  • female adults