我编写了以下方法,该 boolean 返回类型再次分配给我调用此方法的另一个方法中的另一个 boolean 值。
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while(answer != "y" || answer != "n") {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer == "y") {
b = true;
}
return b;
}
但是无论我输入什么(y、n 或任何其他字母),我总是会再次陷入 while 循环。
最佳答案
这是因为您的测试中使用的是 or
而不是 and
。
按照当前的编码,您所说的是:
while the answer isn't "y" or it isn't "n", loop.
情况永远如此。
你想要的是:
while the answer isn't "y" and it isn't "n", loop.
编码为:
while (answer != "y" && answer != "n") (
关于java - 如何摆脱这个 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34119551/