Java 如何使用或来比较字符串。。。

Java 如何使用或来比较字符串。。。,java,string,while-loop,operators,Java,String,While Loop,Operators,//当用户键入y或n时,我需要中断while循环。。但到目前为止,我只能用一个字母/字符串得到它 Scanner user_input = new Scanner(System.in); String name = user_input.next(); System.out.print("Would you like to order some coffee, "+name+"? (y/n)"); String coffeeYorN = user_input.next(); while (

//当用户键入y或n时,我需要中断while循环。。但到目前为止,我只能用一个字母/字符串得到它

Scanner user_input = new Scanner(System.in);
String name = user_input.next();
System.out.print("Would you like to order some coffee, "+name+"? (y/n)");
String coffeeYorN = user_input.next();

  while (!coffeeYorN.equals("y")||!coffeeYorN.equals"n")  //HERE IS MY ISSUE
  {
    System.out.println("Invalid response, try again.");
    System.out.print("Would you like to order some coffee, "+name+"? (y/n)");
     coffeeYorN = user_input.next();
  }

我肯定这个问题以前有人回答过,但我找不到

你的if语句说“如果不是y或n”,这永远是真的,因为有些东西不能同时是“y”和“n”


如果要使用“and”,而不是“or”。

当条件为true时,请执行此循环

假设有人输入“n”

你的条件是:

输入不是“y”吗?是的,它是“n”,所以我应该执行循环。

你需要这样的东西:
while(!coffeeYorN.equals(“y”)和&!coffeeYorN.equals(“n”)

当用户键入y或n时,我需要中断while循环

那么你的情况应该是:

while (!coffeeYorN.equals("y") && !coffeeYorN.equals("n"))
或者类似的,但更清晰的版本,我想这就是你想要做的:

while (!(coffeeYorN.equals("y") || coffeeYorN.equals("n")))
让我们检查一下真值表:

Y - coffeeYorN.equals("y")
N - coffeeYorN.equals("n")

case   Y N  (!Y || !N)  !(Y || N)
  0    0 0      1           1
  1    0 1      1           0
  2    1 0      1           0
  3    1 1      0           0

您希望条件求值为
true
,并且循环仅在
0
情况下继续运行,此时
Y
N
均不为true,并在所有其他情况下停止。按照您的操作方式,只有当
coffeeYorN
同时等于
“y”
“n”
(case
3
)时,它才会停止。控制台输入不会从字符串转换为字符。你在检查字符。