下面的代码来自一个游戏,我需要在Java中生成2个随机数,并向用户展示其中一个。然后,他们必须猜测第二个数字是高于还是低于第一个数字。我创建了一个while循环来检查其输入中是否有错误,即使条件不成立,也会执行循环。输入H表示他们的猜测是下一个数字更高,而L表示他们认为数字较低。

// 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);

最佳答案

使用&&而不是||。当然不会是H也不是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));
}

关于java - Java while循环不适用于字符的输入检查,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46700445/

10-09 04:29