非脚本语言中类似脚本的行为
我正在玩Java中的三元运算符时,突然想到了这个问题。在 PHP 中,我们可以使用三元运算符进行决策,然后在主文档中放置一些命令(或标签),如下所示(PHP 手册中的示例):
echo (true?'true':false?'t':'f');
现在,在 Java 中是否可以实现类似的操作?比如,有类似下面代码的东西吗?
jButton1.getText().equals("hi")?jLabel1.setText("one"):jLabel1.setText("two")
我想要的是,根据真/假值只执行其中一条语句。我知道使用 if-else
结构可以更好地完成此操作,但我只是出于好奇并提出了这个问题。
I was playing around the ternary operator in Java when suddenly this question came to my mind. In PHP we can use the ternary operator for the decision and then put some command (or tags) in the main document like this (an example from the PHP manual.):
echo (true?'true':false?'t':'f');
Now, is something similar to this possible in Java? Like, is anything similar to the code below possible?
jButton1.getText().equals("hi")?jLabel1.setText("one"):jLabel1.setText("two")
What I want is, only one of the statements should be executed according to the true/false value. I know that this can better be done by using a if-else
construct, but I just got curious and asked this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请使用它:
根据 JLS,该运算符称为 条件运算符。通过阅读前面的链接您可以看到
Use this instead:
According to the JLS, this operator is called the conditional operator in Java. You can see by reading the preceding link that
或者:
JRL 的解决方案更加优雅,但是如果您喜欢根据“hi”操作不同的标签,您可能需要这样的方法。
Or:
JRLs solution is much more elegant, but if you like to manipulate different labels, depending on "hi", you might need such an approach.
Java 肯定有三元运算符。在我看来你使用它是正确的。如果它给我带来问题,我会尝试使用括号,但看起来你使用它是正确的。
Java 术语本周最佳:三元运算符正在解释它。
Java definitely has a ternary operator. It looks to me like you're using it right. I would try to play around with the parenthesis if it was giving me problems, but it looks like you're using it right.
Java Term of the Week: Ternary Operator is explaining it, though.