天天看点

java三元运算符是,三元运算符Java

java三元运算符是,三元运算符Java

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);

解决方案

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.