The completed program is given below.
The program has also been improved by accepting
input from the user.
The program uses the charAt( int index )
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.io.*; class Switcher { public static void main ( String[] args ) throws IOException { String lineIn; char color ; String message = "Color is"; BufferedReader stdin = new BufferedReader ( new InputStreamReader(System.in) ); System.out.println("Enter a color letter:"); lineIn = stdin.readLine(); 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 ) ; } }