串联2个三进制运算符的结果时,字符串串联在Java中无法正常工作 [英] String concatenation does not work properly in Java when concatenating 2 results of ternary operators
问题描述
亲爱的Java专家!
能否请您解释一下,为什么在串联2个三进制运算符的结果时String串联不能在Java中正常工作?
Can you, please, explain me, why String concatenation does not work properly in Java when concatenating 2 results of ternary operators?
示例:
String str = null;
String x = str != null ? "A" : "B" + str == null ? "C" : "D";
System.out.println(x);
输出为"D",但我希望为"BC".
Output is "D", but I expected "BC".
由于运营商的优先考虑,我怀疑它的工作原理是这样,但是我不确定在上述情况下我们究竟如何得到"D".这种情况下会发生什么计算算法?
I am suspecting that it works like so because of operators priorities, but I am not sure, about how we exactly we get "D" for case above. What calculation algorithm takes place for this case?
推荐答案
它解释为以下代码:
String x = str != null ? "A" : ("B" + str == null ? "C" : "D");
"B" + str
不为null,因此它将被评估为"D"
"B" + str
is not null so it will be evaluated as "D"
借助OSborn的答案,您可以使用以下代码完成您期望的事情:
With help of OSborn's answer you can do what you expect with this code:
String x = (str != null ? "A" : "B") + (str == null ? "C" : "D");
,由于您只是将str
与null
进行比较,并且两个条件语句几乎相同,因此可以将其缩短:
and since you are just comparing str
with null
and both conditional statements are almost the same, it can be shortened like this:
String x = (str != null ? "AD" : "BC");
这篇关于串联2个三进制运算符的结果时,字符串串联在Java中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!