Fixed Program

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:

The correct program fragment is given below.

Fixed Program

Here is the corrected program. It would be OK if you put a break after the statment in the default case, but it is not needed.

class Switcher
{
  public static void main ( String[] args )
  {
    char   color = 'Y' ;    
    String message = "Color is";
    
    switch ( color )
    {
    
      case 'R':
        message = message + " red" ;
        break;
                        
      case 'O':
        message = message + " orange" ;
        break;
                        
      case 'Y':
        message = message + " yellow" ;
        break;
                        
      case 'G':
        message = message + " green" ;
        break;
                        
      case 'B':
        message = message + " blue" ;
        break;
                        
      case 'V':
        message = message + " violet" ;
        break;
                        
      default:
        message = message + " unknown" ;
            
    }

  System.out.println ( message ) ;
  }
}

Often what you really want is for several characters to select a single case. This can be done using several case statments, followed by just one list of statments. For example, here both 'y' and 'Y' select the same statement:

      case 'y':                        
      case 'Y':
        message = message + " yellow" ;
        break;

QUESTION 10:

Mentally insert extra case statements into the program so that upper and lower case characters work for each color. (Or, even better: copy the program to an editor, fix it, and run it.)