// This is my test code
int i = a == 1? c = 3: d = 4; // error message
// And when the Intellij rewrite it in form of if clause
int i;
if (a == 1) i = c = 3 = 4;
else i = d = 4;
// Another code
int i = a == 1? (c = 3): (d = 4); // work
// If clause
int i;
if (a == 1) i = c = 3;
else i = d = 4;
有人可以解释一下每种情况下发生的情况吗?为什么表达式 2 和 3 需要括号括起来?
最佳答案
这是由于Operator Precedence .
三元运算符?:
的优先级高于赋值运算符=
。这意味着 a == 1 ?首先计算 c = 3: d
,然后计算 = 4
。
该语句等于int i = (a == 1 ? c = 3 : d) = 4;
。但这不是有效的 java,因为您无法将值分配给值。
您已经通过使用括号()
解决了这个问题,它表明(就像在普通数学中一样)应该首先评估其中的所有内容。
关于Java引用条件表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60725312/