user1661235
user1661235

Reputation:

While loop to check character input

I am trying to accept input from the user in the form of a character. I have that working but I need to check and make sure it is one of 6 characters (H, h, S, s, L, l). I have a while loop but as soon as add more than one character statement to it, the loop gives the error for every value that should be correct.

Here is the function:

    private static char getHighLow(Scanner keyboard) 
{
    System.out.println("High, Low, or Sevens (H/L/S): ");
    String choiceString = keyboard.next();

    char choice = choiceString.charAt(0);

    while (choice != 'H' || choice != 'h' || choice != 'L' || choice != 'l' || choice != 'S' || choice != 's')
    {
        System.out.println("You have entered an invalid entry.");
        System.out.println("High, Low, or Sevens (H/L/S): ");
        choiceString = keyboard.next();
    }

    return choice;

}

What is the best way to continue checking for multiple characters like this?

Upvotes: 0

Views: 27993

Answers (3)

pb2q
pb2q

Reputation: 59607

There is an error in your logic: you should be connecting those tests with AND: &&:

while (choice != 'H' && choice != 'h' && choice != 'L' && ...

Furthermore choice is never being updated within the body of the loop, so it will never change. Duplicate the choice = choiceString.charAt(0); after you re-read choiceString within the loop.

Conceptually, you want to keep asking for input so long as the character isn't H AND isn't L AND isn't S.

Upvotes: 3

Baz
Baz

Reputation: 36884

You never update choice in your while loop:

Just add this line at the end of your loop:

choice = choiceString.charAt(0);

Moreover you should check with && rather than ||.

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361585

Use && instead of ||.

while (choice != 'H' && choice != 'h' && choice != 'L' && choice != 'l' && choice != 'S' && choice != 's')

This can be simplified by converting to lower case first.

choice = Character.toLowerCase(choice);

while (choice != 'h' && choice != 'l' && choice != 's')

Upvotes: 4

Related Questions