Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!= 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;
  }
like image 525
llamagish Avatar asked Dec 22 '25 09:12

llamagish


2 Answers

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

like image 81
Ishara Madhawa Avatar answered Dec 23 '25 23:12

Ishara Madhawa


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
like image 27
MinA Avatar answered Dec 23 '25 22:12

MinA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!