Taylor Taylor - 10 days ago 5
Java Question

Incompatible types: int and boolean. How to re-write if statement?

I'm trying to write this if statement:

public void currentState(boolean x)
{
boolean timeOn = true;
boolean timeOff = false;
if (x ==(0)) {
x = timeOff;
} else {
x = timeOn;
}
}


if (x ==(0)
does not work which I fully understand, but how would you re-write this so that x can be compared to 0?

Answer

You can only use two values - true and false if you're dealing with boolean. 0 is not one of them.

You could write the statement like this:

if (x == false) {
    x = timeOff;
} else {
    x = timeOn;
}

However, this if statement is meaningless. It is equivalent to:

if (x == false) {
    x = false;
} else {
    x = true;
}

It basically says "if x is false, make it false". You might want to reconsider what your method does.

EDIT:

You can also rewrite it like this:

if (x == true) {
    x = timeOff;
} else {
    x = timeOn;
}

which is equivalent to:

if (x) {
    x = timeOff;
} else {
    x = timeOn;
}

which is equivalent to:

x = !x;