Mik
Mik

Reputation: 29

How can I compare a string using or ||...

//I need the while loop to break when the user types y OR n.. but so far I can only get it for one letter/string.

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();
  }

Upvotes: 2

Views: 42

Answers (3)

Anderson Vieira
Anderson Vieira

Reputation: 9059

I need the while loop to break when the user types y OR n

Then your condition should be:

while (!coffeeYorN.equals("y") && !coffeeYorN.equals("n"))

Or the equivalent, but a bit clearer version, which I think is what you wanted to do:

while (!(coffeeYorN.equals("y") || coffeeYorN.equals("n")))

Let's check the truth table:

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

You want the condition to evaluate to true and the loop to keep going only in case 0, when neither Y or N are true, and stop for all the other cases. The way you did it, it will stop only if coffeeYorN is equal to "y" and "n" at the same time (case 3), which can never happen.

Upvotes: 2

shieldstroy
shieldstroy

Reputation: 1327

While the conditional is true, execute this loop.

Let's say someone enters "n"...

Your conditional says:

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

You need something like this: while(!coffeeYorN.equals("y") && !coffeeYorN.equals("n"))

Upvotes: 1

Carl
Carl

Reputation: 991

I'm sure this has been answered before, but I can't find it.

Your if statement says "if it's not y or n", which will always be true, because something can't be "y" and "n" at the same time.

You want to use "and", rather than "or".

Upvotes: 1

Related Questions