FinalFind
FinalFind

Reputation: 131

Can someone Explain Why This While Statement Has to be AND

So basically I am having some trouble understanding the logic that is not allowing this statement to use "OR" but to work perfectly using "AND". By my logic saying equals Y or y or N or n, should work. But if I use this its an infinite loop. The code block can be seen below;

      response = "empty";
      while (!response.equals("Y") && !response.equals("y") && !response.equals("N") && !response.equals("n"))
      {
          response = stdin.next();
          if (!response.equals("Y") && !response.equals("y") && !response.equals("N") && !response.equals("n")) {
              System.out.println("Try again, you're still in the loop!");
          }
          else {
              System.out.println("Congratulations you're out the loop!");
          }

      }
  }

Could anyone explain to me the logical reason that || cannot be using but && works perfectly. The rest of the code (scanner etc are above but I havent included them as they are not relevant). Thanks!

Upvotes: 2

Views: 151

Answers (4)

Amir Afghani
Amir Afghani

Reputation: 38521

There is a lot you can do to improve this code. Consider

response = stdin.next();
while (!response.equalsIgnoreCase("y") || !response.equalsIgnoreCase("n"))
{
   System.out.println("Try again, you're still in the loop!");
   response = stdin.next();                
}
System.out.println("Congratulations you're out the loop!");

@Eran's answer explains why your logic is wrong.

Upvotes: 0

Rakesh KR
Rakesh KR

Reputation: 6527

&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.

|| Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.

enter image description here

Upvotes: 0

Eran
Eran

Reputation: 393781

You can do it with or :

while (!(response.equalsIgnoreCase("Y") || response.equalsIgnoreCase("N")))

Since

(!A && !B && !C) is equivalent to !(A || B || C)

It's called De Morgan's Law.

In addition, it would be better to have the condition in only one place :

response = stdin.next();
while (!(response.equalsIgnoreCase("Y") || response.equalsIgnoreCase("N")))
{
    System.out.println("Try again, you're still in the loop!");
    response = stdin.next();
}
System.out.println("Congratulations you're out of the loop!");

Upvotes: 4

Fawar
Fawar

Reputation: 735

It is because you want the response not to Y, nor y nor N nor n.

Doing OR || would crash the logic has if you are Y you ain't y and therefore OR would return true

|| would make the statement be true at all time.

With X

True since it would not be Y, nor y, nor N, nor N So True or True or True or True == True

If you put any of the condition (Y, y, n, N) it would give True OR true OR true OR false (in various order) == true

Upvotes: 0

Related Questions