1
Scanner in = new Scanner(System.in);   

      String err = "\nThat's not a card color!\n\n";

 System.out.print("Is your card red, green or blue? ");
    String card = in.nextLine();
        if ((!"red".equals(card))){
            System.out.print(err);
             System.exit(0);
        }

The user has to input a string that equals either 'red', 'green', or 'blue'. I have it working fine for just 'red', but how do I have it check MULTIPLE strings?

Thank you all! It is now working. Sorry I am kind of new to Java. I tried an else if before but now that the

    System.out.print(err);
    System.exit(0);

is in an else statement it is working perfectly!

4 Answers 4

3

Make an array of Strings you want to check and then iterate over it, like this:

boolean foundColor = false;
for(String color:new String[]{"red","green","blue"}){
    if (color.equals(card)){
        foundColor = true;
    }
}
if(!foundColor){
    System.out.print(err);
    System.exit(0);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This will actually print the error regardless of the input because no string can be red, green, and blue at the same time.
@Njol You're absolutely correct. Silly mistake on my part. Just corrected it.
1

Here's a one-liner if you want to make your code more concise:

if (!Arrays.asList("red", "green", "blue").contains(card)) {
    System.out.print(err);
    System.exit(0);
}

Comments

0

Consider:

If "red", else if "green" else if "blue", else print "wrong!"

1 Comment

Thanks but I have already tried putting it in an 'else if' statement. Oh, so put the wrong in an else and do not include a '!' It worked! Many thanks kind sir!
0

what you do is to check if the card is red if its not red the input is wrong, but what you want to do is check for every color and if after all the input matches no string you print the error.

so just go like

if(card.equals("red")){
 ... do something
}
else if( card.equals("blue"){
 ... do something else
}
else
  error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.