38.1k views
5 votes
Write piece of code that reads a shorthand text description of a color and prints the longer equivalent. Acceptable color B for Blue, G for Green, and R for Red. If the user types something other than B, G, or R, the program print an error message. Make your program case-insensitive so that the user can type an uppercase or lowercase letter. Here are some example executions: What color do you want? B You have chosen Blue. What color do you want? g You have chosen Green. What color do you want?

1 Answer

6 votes

Answer:

Scanner console = new Scanner(System.in);

System.out.print("What color do you want? ");

String choice = console.next();

if (choice.equalsIgnoreCase("r")) {

System.out.println("You have chosen Red.");

}else if (choice.equalsIgnoreCase("b")) {

System.out.print("You have chosen Blue.");

}else if (choice.equalsIgnoreCase("g")) {

System.out.print("You have chosen Green.");

}

else{

System.out.print("Unknown color: " + choice);

}

User Peter Wiley
by
5.3k points