The Conditional Operator and the 'switch' Statement
15. Example with Strings
Answer:
"BTW".equals( " BTW ")
is false
Blank spaces matter in string comparison.
Example with Strings
Here is a program that asks the user for an acronym and then prints out its meaning:
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?