【问题标题】:Logical OR does not work properly in the while loop逻辑 OR 在 while 循环中无法正常工作
【发布时间】:2023-03-25 12:59:02
【问题描述】:

问题在于,while 循环中的第一个条件即使为真,也根本不会被执行。如果我从 while 循环中删除逻辑 OR 并只写第一个条件(selection.compareToIgnoreCase("O") >0)它工作正常。但是如果逻辑或有两个条件,就不行了。

我尝试过使用equals(),我也尝试过使用否定逻辑 while(!selection.equals("O") || !selection.equals("E"))。第二个条件很好,但第一个根本不起作用。

public class OddsOrEvens {
public  static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
    System.out.println("Let’s play a game called \"Odds and Evens\"");
    System.out.println("Whats your name ? ");
    String name = sc.nextLine();
    System.out.println("Hi "+ name +", which do you choose? (O)dds or (E)vens?");
    String selection = sc.nextLine();
    System.out.println("selection: " + selection);

    while (selection.compareToIgnoreCase("O") >0 || selection.compareToIgnoreCase("E") >0){
        System.out.println("Please enter the correct choice. Select 'O' for odds or 'E' for evens");
        selection = sc.next();
    }

    if(selection.equalsIgnoreCase("O")){
        System.out.println(name + " has picked Odds! The computer will be evens.");
    }else if (selection.equalsIgnoreCase("E")){
        System.out.println(name + " has picked Evens! The computer will be Odds.");
    }
}

}

【问题讨论】:

  • 你真的应该写出你的条件的真值表。
  • 你试过调试吗?
  • selection.compareToIgnoreCase("O") >0 正在检查选择是否大于 "O". Try selection.compareToIgnoreCase("O") == 0`。
  • 是的,我尝试过调试,变量(Selection)中的值总是如预期的那样,但循环不能正常工作。
  • @oldCurmdgeon 如果我将其更改为 == 那么它将进入无限循环。

标签: java while-loop conditional logical-operators


【解决方案1】:

您的字符串比较不正确。 Compareto 为小于/等于/大于返回 -1/0/1。

更清晰的方法是使用toUppercase().equals(...

    while (!selection.toUpperCase().equals("O") && !selection.toUpperCase().equals("E")){

【讨论】:

    【解决方案2】:

    这是不支持两种情况,需要!... && ! ...|| 将具有始终为真的效果,因为至少有一种情况为假。或者!(... || ...)

    while (!selection.equalsIgnoreCase("O") && !selection.equalsIgnoreCase("E")) {
    

    让我们简化一下:

    !(n == 1) || !(n == 2)       // WRONG
      n != 1  ||   n != 2        // WRONG
    

    将永远为真,因为 n == 1 为假或 n == 2 为假:至多一个选择可以为真,而伪造其他选择。所以至少在一边是 !false, true,所以整个表达式是 true。

    !(n == 1) && !(n == 2)       // GOOD
      n != 1  &&   n != 2        // GOOD
    

    心理上的错误是语言上的 OR 主要意味着 EXCLUSIVE OR。

    可能是等价的:

    !(n == 1 || n == 2)      <=>      n != 1 && n != 2   [De Morgan's law]
    

    【讨论】:

    • 我现在明白多了。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 2021-09-26
    • 2014-12-06
    相关资源
    最近更新 更多