【问题标题】:How can I compare a string using or ||...如何使用或 || 比较字符串...
【发布时间】:2015-06-29 12:15:58
【问题描述】:

//当用户键入 y OR 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();
  }

【问题讨论】:

    标签: java string while-loop operators


    【解决方案1】:

    当用户键入 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,并且循环仅在0YN 都不为真时继续进行,并在所有其他情况下停止。按照您的操作方式,只有当coffeeYorN 等于"y""n" 同时(案例3)时它才会停止,这永远不会发生。

    【讨论】:

      【解决方案2】:

      当条件为真时,执行此循环。

      假设有人输入“n”...

      你的条件说:

      Is the input something other than "y"? Yes, it is "n", so I should execute the loop.

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

      【讨论】:

      • 控制台输入未从字符串转换为字符。您正在检查字符。
      【解决方案3】:

      我确定以前已经回答过这个问题,但我找不到。

      你的 if 语句说“如果它不是 y 或 n”,这将永远是正确的,因为某事不能同时是“y”和“n”。

      你想使用“and”,而不是“or”。

      【讨论】:

        猜你喜欢
        • 2022-07-22
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        相关资源
        最近更新 更多