If you want to save lines, you can come up with a pretty ugly ternary statement:
currentFoodAmount = currentFoodAmount > maxFoodAmount ? maxFoodAmount : (
currentFoodAmount < 0 ? 0 : currentFoodAmount);
It's admittedly really hard to read, but if you're into saving lines of code, here you go.
More on Ternary
The ternary operator operates on a single conditional which evaluates to either true
or false
and then returns the value corresponding to the result.
Meaning if you have a statement like this:
x = y == 0 ? 1 : 2;
Your x
variable will be set to 1
if y == 0
. If y != 0
, then x
will be set to 2
;
The ternary format in Java looks like this:
conditional ? trueValue : falseValue;
Do note that this technique is often frowned upon, as it often makes code difficult to read as opposed to a more verbose if
/else
clause.