Sapus Boh Sapus Boh - 2 months ago 9
Java Question

The operator -= is undefined for the argument type(s) double, boolean

I was developing something. But an error appears, and i cannot fix it.
It says ''The operator -= is undefined for the argument type(s) double, boolean'' on my code:

if (x -= 15.0D < 0.0D) {


I'm just leaving out a part of my code. Anyone knows how to fix it? I cannot get it work. Thank you :)

Answer

Because of the way operator precedence is defined in Java, -= has lower precedence than <; as such, x -= 15.0D < 0.0D is evaluated as:

x -= (15.0D < 0.0D)

or

x -= false

which is not a valid expression in Java because, like the error says:

The operator -= is undefined for the argument type(s) double, boolean

The fix depends upon what you are trying to express:

  • If you intend to say "subtract 15 from x, then compare x to zero", you can write this as:

    (x -= 15.0) < 0.0
    

    However, conditionals with side effects (e.g. changing a variable's value) are confusing because it's easy to misread them, ignoring the side effect. It is more readable (and I would guess semantically identical) to write:

    x -= 15.0;
    if (x < 0.0) {
    
  • If you intend to say "if x - 15 is less than zero", you don't use the -= operator, just use plain -:

    if (x - 15.0 < 0.0)
    

    Note that inner brackets are not required here, because - has higher precedence than <.

    But then it's also easier to express this as:

    if (x < 15.0) {
    

Note that you don't need the D suffix: provided you have a decimal point in the literal, and don't use the F suffix to make it a float, a decimal literal is of double type.

15.   15.0  15D  15.D  15.0D

are all valid double literals with the same value. (Personally, I don't like the one ending with a .; it looks incomplete to me).

Comments