This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
It's just a matter of logic. This condition:
Is true if x isn't 1 or if x isn't 2 or if x isn't 3. Since it can't be all three at the same time, this will always be true. You need to AND the conditions, not OR them.
So you can get the effect you intended using:
Joined: Nov 04, 2005
Wow - that seemed pretty obvious. Can't believe I missed that...THANK YOU!
I just want to point something out...Your subject doesn't really match the issue you are asking about. "Can't" to me implies that it isn't allowed - i.e. you get some kind of compiler error.
However, what was really happening was that you COULD use it, but it didn't behave like you thought it should. That is what we mean by TellTheDetails. Tell us what REALLY happens, and what you EXPECT to happen. Generally, it makes helping you much easier, and the easier it is to help you, the more likely you are to get help.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
What happens with operators like < > == != etc is that their argument types and types are different.
Let’s see if I can explain it simply. Let’s look at some ordinary arithmetic operators. 1 + 2. Keep it nice and simple
1 is an int
2 is an int
+ can take two ints
+ on two ints has the type int.
So 1 + 2 as a whole expression is an int.
Now try 1 + 2 + 3.
The JVM evaluates that expression from left to right, and the operator priorities are consistent with ordinary arithmetic. So, what stage are we at halfway through the evaluation?
(1+2allDoneAndEvaluated) + 3
Now we know that 3 is an int, and we have already seen that (1+2allDoneEtc) is also an int. So we are supplying the + operator with two ints, and the compiler is happy.
What about != ? It can take two ints, but it returns a boolean. So if you try i != j != k, you get this sort of thing, assuming i j and k are all ints.
i is an int
j is an int
!= can take two ints
!= on two ints has the type boolean [First difference from 1 + 2]
Evaluating from left to right, exactly as before.
(i!=jAllDoneEtc) != k
(i!=jAllDoneEtc) has the type boolean, and k has the type int.
The != operator cannot cope with mixed types (boolean != int) like that. So the compiler will complain. You probably get an error message like “expected boolean found int”.
Damn! I have answered the wrong question. Well, you can have the answer anyway. It matches the original question better.