Java ternary operators and same-variable assignment

102 Views Asked by At

I was creating a class to use as a backbone for creating an item with durability in games (much like a pick or sword in Minecraft) and ran across an error while creating a method which contained a ternary operator:

public void setMaxDurability(int newMax) {
    newMax > MAX_DURABILITY ? maxDurability = MAX_DURABILITY : maxDurability = newMax;
}

This code throws an error at the ">" operator in Eclipse, saying "Syntax error on token ">", -> expected." For clarificiation, newMax is the new maximum durabilty to set the variable maxDurability to, but it cannot be greater than the constant MAX_DURABILITY. All types are int (and the constant is final), so I don't understand what the problem is.

I managed to get the method to work using

public int setMaxDurability(int newMax) {
    return maxDurability = (newMax > MAX_DURABILITY ? MAX_DURABILITY : newMax);
}

but I was wondering why the first code block didn't work. Any help?

1

There are 1 best solutions below

0
On

Should be :

public void setMaxDurability(int newMax) {
    maxDurability = newMax > MAX_DURABILITY ? MAX_DURABILITY : newMax;
}