Java while 循环不支持字符输入检查
Java while loop not working with input checking of characters
下面的代码来自一个游戏,我需要在 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 中生成 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));
}