Skip to main content

Section 6.3 Worked Example: Write Switch Statements

Subgoals for Writing Selection Statements.

If Statement
  1. Define how many mutually exclusive paths are needed
  2. Order from most restrictive/selective group to least restrictive
  3. Write if statement with Boolean expression
  4. Follow with true bracket including action
  5. Follow with else bracket
  6. Repeat until all groups and actions are accounted for
OR Switch Statement
  1. Determine variable / expression for mutually exclusive ranges
  2. Write switch statement based on variable / expression
  3. Each range is a ‘case’
  4. Include break statements and default case if needed

Subsection 6.3.1

You can watch this video or read through the content below it.

Subsection 6.3.2 Problem Statement

Write the Java selection statements to solve the following specifications:
Write the statements to print out the name of the month equivalent to the value stored in the integer variable month.

Subsection 6.3.3 SG1: Determine variable / expression for mutually exclusive ranges

In this case there are 12 different months. Each value is represented by a unique value (1 to 12). So a switch statement will work. We want to base it off of the integer variable month.

Subsection 6.3.4 SG2: Write switch statement based on variable / expression

switch (month)
{


}

Subsection 6.3.5 SG3: Each range is a ‘case’

switch (month)
{
   case 1: System.out.println("January");
   case 2: System.out.println("February");
   case 3: System.out.println("March");
   case 4: System.out.println("April");
   case 5: System.out.println("May");
   case 6: System.out.println("June");
   case 7: System.out.println("July");
   case 8: System.out.println("August");
   case 9: System.out.println("September");
   case 10: System.out.println("October");
   case 11: System.out.println("November");
   case 12: System.out.println("December");
}

Subsection 6.3.6 SG4: Include break statements and default case if needed

We only want 1 month to print, without falling through to the next case, so every case needs a break.
switch (month)
{
   case 1: System.out.println("January"); break;
   case 2: System.out.println("February"); break;
   case 3: System.out.println("March"); break;
   case 4: System.out.println("April"); break;
   case 5: System.out.println("May"); break;
   case 6: System.out.println("June"); break;
   case 7: System.out.println("July"); break;
   case 8: System.out.println("August"); break;
   case 9: System.out.println("September"); break;
   case 10: System.out.println("October"); break;
   case 11: System.out.println("November"); break;
   case 12: System.out.println("December"); break;
   default: System.out.println("Invalid value of month.");
}
You have attempted of activities on this page.