tags:

views:

172

answers:

5

what is the java syntax for saying

if x is not equal to a or b

I am trying to write an if else statement .. if a certain value is not equal to say 2 or 3 then do something else do something else :) thats confusing lol

+1  A: 
if( x != a && x != b )

Notice it's an &&, not an ||

The condition ( x != 2 || x != 3 ) is always true: if x = 2, then x != 3 and the condition is true. if x = 1, then x != 2 and the condition is true.

What you're really saying is: if x is not one of 2 or 3, which is, x is not in the array [2,3], which is "x is not 2 neither 3", which is x != 2 and x != 3.

hasen j
A: 
if(x!=a && x!=b){
  //do...
}
Cesar
Uppercase variable names is not recommended in Java.
Asaph
@Asaph: as if *that* is the problem
hasen j
@Asaph: They may be constants. More worrying is the fact that the condition is wrong... it should be an "and" rather than an "or".
Jon Skeet
Thanks for pointing that out, corrected the answer. Think i need some sleep.
Cesar
+1  A: 
if ((x != a) && (x != b)) {
    // do stuff
} else {
    // do other stuff
}
Ken Browning
+12  A: 

Try this:

if (x != a && x != b) {
  // Something (action x)
} else {
  // Something else (action y)
}

Note that it's an "and" condition even though you're asking whether x is equal to a or b because each condition is negative. The other way you could represent this (if you find it more readable) is:

if (!(x == a || x == b)) {
  // Something (action x)
} else {
  // Something else (action y)
}

And at that point you may find it more readable still to get rid of the negation, but switch round what you do in the blocks:

if (x == a || x == b) {
  // Action y
} else {
  // Action x
}

These three blocks of code all do the same thing, but I think I'd find the bottom one the most readable as the condition is simple.

Jon Skeet
A: 

directly mimics the english sentence: if x is not equal to a or b

if (!(x == a || x == b))
{
    doSomething();
}
else
{
    somethingElse();
}

but if the extra not operator and parentheses hurts your eyes, use this(note the absence of the word Or in this condition, not anymore parallel with english sentence):

if (x != a && x != b) 
{
    doSomething();
}
else
{
    somethingElse();
}

see my answer on programmer's ignorance pet peeve and Is it acceptable to only use the ‘else’ portion of an ‘if-else’ statement?, why i advocate constructing simple conditions(directly mimics english sentence, i.e. without sticky ANDs and too much NOTs)

Michael Buen
It's advisable to include the curly braces even though they are technically optional on one liners. Let's set a good example for the noobs.
Asaph