<分区>
我有以下一段代码。我是这样理解的。
在第一种情况下,三元运算符返回 y
的值,因为 x=4
并且 print 语句按预期打印 5
.
在第二种情况下,三元运算符首先将 y 的值赋给 x,然后返回该值。同样,它按预期打印 5。
在第三种情况下,三元运算符在 : 的左侧有 x=y
,在 的右侧有
。我希望这会像第二种情况一样。但是,此语句甚至无法编译。 x=z
:
任何有助于理解这一点的帮助将不胜感激。
public class Test {
public static void main(String[] args) {
int x = 4;
int y = 5;
int z = -1;
x = (x == 4) ? y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : z; // compiles and runs fine
System.out.println(x + " " + y + " " + z);
x = (x == 4) ? x = y : x = z; // Does not compile
System.out.println(x + " " + y + " " + z);
}
}