Question

Is there a way to have an if-statement with the condition being (x "not"<= 90)? Or is the only way to do that, using (x <= 90) in the if part and doing nothing as a result if that were true, then performing whatever needs to be done in the else? I should mention I'm doing this in Java.

Était-ce utile?

La solution

You can invert the statement with

if(!(x <= 90))

or just change it

if(x > 90)

Autres conseils

The ! sign is called the "not operator" or the "bang symbol".

It "negates" any boolean value that follows it.

You can use it in front of any expression that evaluates to a boolean value.

Example:

int a = 4;
int b = 5;
boolean isGreater = ( a > b );
if (!isGreater) {
    System.out.println("a is NOT greater than b");
}

Sadly, you don't even need to know how to write this as your IDE can do this for you. In IntelliJ if you write

if (x <= 90)
   doSomething();

and you press alt-enter on the if clause, you get an option to flip the condition and it will change it to

if (x > 90) {

} else {
   doSomething();
}

Similarly

if(x <= 90 && x >= 60)

can be refactored to

if (60 <= x && x <= 90)

and flipped to

if (60 > x || x > 90)

and refactored to

if (x < 60 || 90 < x)

without touching the code yourself.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top