Is there a way to implement this in a ternary operation. I'm very new to that ternary stuff, maybe you could guide me.
if(selection.toLowerCase().equals("produkt"))
cmdCse.setVisible(true);
else
cmdCse.setVisible(false);
This one doesn't seem to work.
selection.toLowerCase().equals("produkt")?cmdCse.setVisible(true):cmdCse.setVisible(false);
Here are my tips, if you need to set things to booleans, then simple use setBoolean(condition), else, if you need to set a variable to a non boolean value, then use var=condition?result1:result2(or the variable itself if you don't want to change if condition is false), otherwise, use if else.
Perhaps
The ternary operator isn't exactly like an if statement. A ternary operator has to "return" something from both sides, so putting void method calls like setVisible() there won't work.
Instead, you could do something like this without ternary operators at all:
But just to demonstrate the point, the ternary equivalent would look something like this:
Notice how now the ternary operator "returns" true or false on both sides instead of simply calling a void method.
In this case, you don't even need a ternary operator:
Or, cleaner:
Your version:
is semantically incorrect: ternary operator should represent alternative assignments, it's not a full replacement for
if
statements. This is ok:because you are assigning either
x
orMath.sqrt(y)
towow
, depending on a condition.My 2cents: use ternary operator only when it makes your program clearer, otherwise you will end up having some undecipherable one-liners.
I think this will work for you
Directly from the docs
In your case
cmdCse.setVisible(true / false);
doesn't return anything, and the operation also has side effects (it changes state ofcmdCse
), so the conditional operator cannot be used here (when you do use the operator, both of the?
and:
branches must have the same return type).As an aside, please note that
.. ? .. : ..
should be referred to as theconditional operator