三元运算符Java [英] Ternary Operators Java

查看:189
本文介绍了三元运算符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);

这个似乎不起作用。

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)取决于条件

我的2cents:只有当你的程序更清晰时才使用三元运算符,否则你最终会得到一些难以理解的单行代码。

My 2cents: use ternary operator only when it makes your program clearer, otherwise you will end up having some undecipherable one-liners.

这篇关于三元运算符Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆