javaloopserror-handlinglogicdrjava

Java while loop not working with input checking of characters


The code below is from a game in which I need to generate 2 random numbers in java, and the user is presented with one of them. They then have to guess if the second number is higher or lower than the first. I created a while loop to check for errors in their input and the loop is executed even if the condition is not true. Entering H means their guess is the next number is higher, and L means they believe its lower

// Input 
System.out.println ("Do you think the second number is higher or lower (enter 'H' or 'L' respectively): ");
char userGuess = Character.toUpperCase(input.next().charAt(0));

// Input error check (and immediate output of second number)
while (userGuess != 'H' || userGuess != 'L') {
    System.out.println ("Sorry, I didn't understand that. Please try again: ");
    userGuess = Character.toUpperCase(input.next().charAt(0));    
}
System.out.println ("The second number was " + secondRandomNumber);

Solution

  • Use && not ||. Of course it's not going to be H or not going to be L

    while (userGuess != 'H' && userGuess != 'L') {
        System.out.println ("Sorry, I didn't understand that. Please try again: ");
        userGuess = Character.toUpperCase(input.next().charAt(0));    
    }