llamagish
llamagish

Reputation: 209

!= operator doesn't seem to be working when comparing a variable to an integer

All I'm trying to do is create a validation loop if the user enters anything other than "1" or "2"... but when I test the program, regardless of what number I entered (including 1 and 2), the validation loop prompts. Am I blind?? I can't see what's wrong with this syntax.

public static int getValidShiftNbr(String msg)
  {
    int nbr = IR4.getInteger(msg);
    while ((nbr != 1) || (nbr != 2))  <===================================
    {
      System.err.println("Error: Please enter either 1 (for day shift) or 2 (for night shift)");
      nbr = IR4.getInteger(msg);
    }
    return nbr;
  }

Upvotes: 2

Views: 193

Answers (4)

MinA
MinA

Reputation: 405

in your code:

if (nbr == 1); what happen is

nbr != 1 => false
nbr != 2 => true

(false) || (true) => true since it is OR operator

to achieve what you want is using a AND operator

(nbr != 1) && (nbr != 2)

1) if (nbr == 1)

(nbr != 1) && (nbr != 2) // false AND true => false

2) if (nbr == 2)

 (nbr != 1) && (nbr != 2) // true AND false => false

3) if (nbr == 3)

(nbr != 1) && (nbr != 2) // true AND true => true

Upvotes: 2

Ishara Dayarathna
Ishara Dayarathna

Reputation: 3601

If you use an OR || it only needs to satisfy one of the conditions, in your case if you enter 1 OR 2 the condition will be true.

You want to use the AND && operator to make sure it neither of them, as shown below:

while ((nbr != 1) && (nbr != 2))

OR

while (!((nbr == 1) || (nbr == 2)))

Here the condition will be true for any number other than 1 and 2

Upvotes: 4

user3437460
user3437460

Reputation: 17454

When you write:

while ((nbr != 1) || (nbr != 2))

It will always be true because whatever input you give will always trigger either (nbr != 1) or (nbr != 2)

If you only want the user to input only 1 or 2:

while ((nbr != 1) && (nbr != 2))

Or

while (!((nbr == 1) || (nbr == 2)))

Upvotes: 1

Phil Benamy
Phil Benamy

Reputation: 11

!= is working, || (which is or) is also working all values of nbr will be != to 1 OR THEY WILL BE != to 2 (possibly both)

btw: nbr is an inferior variable name-- better names would be number or shift

btw: I suggest using n or N or d or D the identify the shift because the computer should do the work, instead of the human

your code should be

while ((nbr != 1) && (nbr != 2))

Upvotes: 1

Related Questions