In: Computer Science
in Java, I am writing a program where you need to pick a color. The color must be red, blue, or green and is a user input. If they put in a different value I need the program to stop running. So I essentially need to write code that says, if variableColor does not equal "red", "blue", or "green" then I need to print the statement "invalid response" and exit the program. How can I write this?
import java.util.Scanner;
public class ColorChooser {
public static void main(String[] args)
{
String color;
Scanner scan = new
Scanner(System.in);
// input the color
System.out.print("Enter a color:
");
color = scan.nextLine();
// validate color is in ["red",
"blue" , "green"] in any case, if not display invalid
response
if(!color.equalsIgnoreCase("red")
&& !color.equalsIgnoreCase("blue") &&
!color.equalsIgnoreCase("green"))
System.out.println("Invalid response");
else
{
// perform the
steps required
System.out.println("Valid response");
}
}
}
//end of program
Output: