Upper and Lower Case

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 completed program is given below.

Upper and Lower Case

The program has also been improved by accepting input from the user. The program uses the charAt( int index ) method of the String class. This method returns a single character from a string. The first character in a string is at index 0, the next is at index 1, and so on. (Remember: a String is an object, even if it contains only one character. The charAt() method must be used here to get a char that can be used in the switch.)

import java.util.Scanner;
class Switcher
{
  public static void main ( String[] args ) 
  {
    String lineIn;
    char   color  ;    
    String message = "Color is";
    
    Scanner scan = new Scanner( System.in );

    System.out.print("Enter a color letter: ");
    lineIn = scan.nextLine();
    color = lineIn.charAt( 0 );  // get the first character

    switch ( color )
    {
    
      case 'r':
      case 'R':
        message = message + " red" ;
        break;
               
      case 'o':                  
      case 'O':
        message = message + " orange" ;
        break;
               
      case 'y':                  
      case 'Y':
        message = message + " yellow" ;
        break;
               
      case 'g':                  
      case 'G':
        message = message + " green" ;
        break;
               
      case 'b':  
      case 'B':
        message = message + " blue" ;
        break;
               
      case 'v':  
      case 'V':
        message = message + " violet" ;
        break;
                        
      default:
        message = message + " unknown" ;
            
    }

  System.out.println ( message ) ;
  }
}

QUESTION 11:

What would be wrong if the program were altered to something like:

switch ( lineIn )
{

  case "red":
  case "Red":
    message = message + " red" ;
    break;

. . . and so on