Java: Checking contents of char variable with if condition
I have a char variable that is supposed to contain either a Y,y,n or N character, I want to test if it does not contain it, then display an error message and exit the program.
This is the code I am using;
if (userDecision != 开发者_Python百科'Y' || userDecision != 'y' || userDecision != 'n' || userDecision != 'N')
{
System.out.println("Error: invalid input entered for the interstate question");
System.exit(0);
}
Irregardless of what is in the variable it always returns true and executes the command to exit the program, what am I doing wrong?
||
means logical or. You want &&
instead.
if (userDecision != 'Y' && userDecision != 'y' ...
a || b
returns true if either a or b is true. Suppose the userDecision
is 'Y'
. Then
userDecision != 'Y'
is falseuserDecision != 'y'
is trueuserDecision != 'N'
is trueuserDecision != 'n'
is true
So together the condition is true and the if branch is executed.
OTOH, a && b
returns true if both a and b are true, which is what you really need.
Read the first part of the condition aloud: Is the choice different from Y
or y
? The problem is that any character is different either from Y
or y
. You’ve picked the wrong logical operator – if you want to be sure that user picked something else than those characters in the condition, you have to pick &&
, logical and: Is the character different from Y
and also different from y
and etc.
Your condition is "if this is not a or not b" this means it will always be true even if it is a or b. What you want to test for is "if this is not (a or b)" so:
if (! (userDecision == 'Y' || userDecision == 'y' || userDecision == 'n' || userDecision == 'N')) {
System.out.println("Error: invalid input entered for the interstate question");
System.exit(0);
}
If your code contains conditions like this that become long as many alternative chars must be tested for, you can use the switch construct, which makes this case easier to follow:
switch (userDecision) {
case 'y': /*fallthrough*/
case 'Y':
// accepted
break;
case 'n': /*fallthrough*/
case 'N':
// rejected
break;
default:
System.out.println("Error: invalid input entered for the interstate question");
System.exit(0);
}
Change yoiur ORs to ANDs
Or you could use
(!(userDecision == 'Y' || userDecision == 'y' || userDecision == 'n' || userDecision == 'N'))
This
!(A OR B)
is equivelant to
!A AND !B
Have a look at Boolean algebra
De Morgans theorem
NOT (P OR Q) = (NOT P) AND (NOT Q)
NOT (P AND Q) = (NOT P) OR (NOT Q)
DeMorgan's Theorem
You need to use &&
instead of ||
. You are asking whether "none" of those characters match, not simply whether any one of the four fail to match. (A value cannot simultaneously be Y, y, N, and n.)
精彩评论