The Conditional Operator and the 'switch' Statement
Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.
11. Upper and Lower Case
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 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:
Could the above program be written using if
statements?