与操作员一起打印报表? :导致意外输出 [英] printing statement with operator ? : causes unexpected output

查看:68
本文介绍了与操作员一起打印报表? :导致意外输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据类似布尔值的状态创建输出

I had to create an output depending on an boolean state like

  String smily = null;
  StringBuffer buff = new StringBuffer();
  buff.append(", " + smily == null ? ":)" : ":("); //$NON-NLS-1$

  System.out.println(buff.toString());

问题是字符串创建语句

  ", " + smily == null ? ":)" : ":("

我在2个不同的月食环境中进行了测试(可能也是2个不同的Java版本,我没有检查过),结果却有所不同.

I tested it in 2 different eclipse environments (and may be also 2 diofferent java version, this i did not checked) and the result was different.

结果1:

:(

结果2:

false:(

false:(

当然,如果我添加了括号,它就可以正常工作

Of course, if i added brackets it is working

 buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$

预期结果:

,:)

请问有人可以解释一下,为什么java用这种方式解释该语句?

谢谢

推荐答案

如果检查运算符优先级(请参阅 => ", null"进行评估,因此", " + smily == null的评估结果为false,因此三元运算符的评估结果为":(".

If you check the operator precedence (see this tutorial), then you will notice that addition (+) comes before equality (==). In other words, Java will first evaluate ", " + smily => ", null" before evaluating equality, therefor ", " + smily == null evaluates to false, and so the ternary operator evaluates to ":(".

BTW:您可以通过在将字符串添加到StringBuffer之前不进行字符串连接来避免这种情况(StringBuffer的全部目的是使连接链接更便宜):

BTW: You could have avoided this by not concatenating strings before adding them to the StringBuffer (the whole point of a StringBuffer is to make concatenation cheaper):

String smily = null;
StringBuffer buff = new StringBuffer();
buff.append(", ");
buff.append(smily == null ? ":)" : ":(");

这篇关于与操作员一起打印报表? :导致意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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