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;
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With