Ternary Operators Java
Solution 1:
In this case, you don't even need a ternary operator:
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
Or, cleaner:
cmdCse.setVisible(selection.equalsIgnoreCase("produkt"));
Your version:
selection.toLowerCase().equals("produkt")? cmdCse.setVisible(true): cmdCse.setVisible(false);
is semantically incorrect: ternary operator should represent alternative assignments, it's not a full replacement for if
statements. This is ok:
double wow = x > y? Math.sqrt(y): x;
because you are assigning either x
or Math.sqrt(y)
to wow
, 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.
Solution 2:
Perhaps
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));