Java while循环不能处理字符的输入检查

时间:2017-10-12 02:27:11

标签: java loops error-handling logic drjava

以下代码来自我需要在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);

1 个答案:

答案 0 :(得分:2)

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