John Marston
John Marston

Reputation: 12269

If statement with String.equals()

if ((clearance.equals("")) || (!clearance.equals("0")) || (!clearance.equals("1"))){
  System.out.println("Invalid entry, exiting.\n");
  System.exit(0);
}

However when I key in 0 or 1 it still prints "Invalid entry, exiting."

Any idea what went wrong?

Upvotes: 1

Views: 529

Answers (4)

digitaljoel
digitaljoel

Reputation: 26574

if clearance is "1" then it's not "0", so you would short circuit there and the value is true. if clearance is 0, then it's not 1 so again your statement is true.

Upvotes: 0

Hot Licks
Hot Licks

Reputation: 47729

Think about it: You're going to print the error message if clearance != "0" OR if clearance != "1". One or the other of those will always be true.

Upvotes: 0

Rob Elsner
Rob Elsner

Reputation: 821

Your logic is wrong.

if ((clearance.equals("")) || ((!clearance.equals("0")) && (!clearance.equals("1")))){

Upvotes: 1

NPE
NPE

Reputation: 500437

The condition should read:

if (!clearance.equals("0") && !clearance.equals("1")) {

Your current expression always evaluates to true (since any string is not equal to either "0" or "1").

Upvotes: 12

Related Questions