Ad

Logical OR Does Not Work Properly In The While Loop

The problem is that, the first condition in the while loop does not get executed at all even if its true. If i remove the Logical OR from the while loop and just write the first condition (selection.compareToIgnoreCase("O") >0) it works fine. But if there are two conditions with Logical OR, it does not work.

I've tried using equals(), I've also tried to negate the logic using while(!selection.equals("O") || !selection.equals("E")). The second condition works fine but the first does not work at all.

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.");
    }
}

}

Ad

Answer

That is for not to hold for two cases, one needs !... && ! ... An OR || would have the effect of being always true, as at least one of the cases is false. Alternatively !(... || ...).

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

Let's simplify:

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

will always be true, as either n == 1 is false or n == 2 is false: at most one choice can be true, falsifying the others. So on at least on side is !false, true, so the entire expression is true.

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

The mental mistake is that the linguistic OR mostly means EXCLUSIVE OR.

Possible would have been the equivalent:

!(n == 1 || n == 2)      <=>      n != 1 && n != 2   [De Morgan's law]
Ad
source: stackoverflow.com
Ad