Many-way Branches

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.

Answer:

number += (number % 2 == 1 ) ? 1 : 0 ;

Many-way Branches

double discount;
char   code = 'B' ;

switch ( code )
{
  case 'A':
    discount = 0.0;
    break;

  case 'B':
    discount = 0.1;
    break;

  case 'C':
    discount = 0.2;
    break;

  default:
    discount = 0.3;
}

Often a program needs to make a choice among several options based on the value of a single expression. For example, a clothing store might offer a discount that depends on the quality of the goods:

  • Class "A" goods are not discounted at all.
  • Class "B" goods are discounted 10%.
  • Class "C" goods are discounted 20%.
  • anything else is discounted 30%.

The program fragment does that. A choice is made between four options based on the value in code.

To execute the switch statement, look down the list of cases to match the value in code. Now execute the statment between the matching case and the following break. All other cases are skipped. If there is no match, the "default" case is chosen.

Warning: the complete rules for switch statments are complicated. Read on to get the details.

QUESTION 5:

If code is 'C', what is the discount?