Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

Ternary Operators 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);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...