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.
15. Example with Strings
Answer:
"BTW".equals( " BTW ")
is false
Blank spaces matter in string comparison.
Example with Strings
import java.util.Scanner; public class StringSwitcher { public static void main ( String[] args ) { String phrase; char color ; String message = "Phrase is: "; Scanner scan = new Scanner( System.in ); System.out.print("Enter Acronym: "); phrase = scan.nextLine().trim().toUpperCase(); switch ( phrase ) { case "LOL": message = message + "Laugh Out Loud" ; break; case "BFF": message = message + "Best Friends Forever" ; break; case "SO": message = message + "Significant Other" ; break; case "THS": case "THKS": case "TX": message = message + "Thanks" ; break; default: message = message + "unknown" ; } System.out.println ( message ) ; } } |
Users might put spaces before or after the acronym. The function String.trim()
removes white space from both sides of a string.
Another problem is that users might enter upper or lower case. The function String.toUpperCase()
creates a string with all upper case.
Question 15:
Could the strings in the case
statements use punctuation?