【发布时间】:2018-01-08 15:08:34
【问题描述】:
这里是代码;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Do you need instructions for this game? Y/N.");
char a = input.next().charAt(0);
// This while loop always comes out as true.
while (a != 'y' || a != 'n') {
System.out.println("Please enter either Y/N. ");
System.exit(0);
}
if (a == 'y') {
System.out.println("This game is called heads and tails.");
System.out.println("You must type h (heads), or t (tails).");
System.out.println("You will need to keep guessing correctly, each correct guess will increase your score.");
}
}
}
有没有解释为什么它总是被证明是真的,有没有其他方法可以做到这一点?我想要进行验证检查,如果用户输入的不是 y 或 n,程序就会关闭。
问题是,当我输入字符 y 或 n 时,即使我使用 !=(不等于)运算符,它仍然会关闭。
【问题讨论】:
-
使用
&&而不是|| -
因为如果a是'y',它肯定不是'n',反之亦然。
-
你需要和&& 不是或||,
y不是n(反之亦然)。
标签: java while-loop constants