问题描述
有没有办法在三元运算中实现这一点.我对三元的东西很陌生,也许你可以指导我.
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);
这个好像不行.
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"));
或者,更清洁:
cmdCse.setVisible(selection.equalsIgnoreCase("produkt"));
您的版本:
selection.toLowerCase().equals("produkt")? cmdCse.setVisible(true): cmdCse.setVisible(false);
在语义上不正确:三元运算符应该表示替代赋值,它不能完全替代 if
语句.没关系:
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;
因为您将 x
或 Math.sqrt(y)
分配给 wow
,取决于条件.
because you are assigning either x
or Math.sqrt(y)
to wow
, depending on a condition.
我的 2cents:只有在让你的程序更清晰的情况下才使用三元运算符,否则你最终会得到一些难以理解的单行.
My 2cents: use ternary operator only when it makes your program clearer, otherwise you will end up having some undecipherable one-liners.
这篇关于三元运算符 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!