我们正在做一项作业,它比较不同边缘的权重,返回 true 或 false,我只需要有人在这里解释老师的代码
boolean thisTest;
int small = (thisTest = u < v) ? u : v,
big = (thisTest) ? v : u;
有人可以解释一下这里的操作吗?
谢谢
最佳答案
相当于:
if u < v
thisTest = true
else
thisTest = false
if(thisTest)
small = u;
else
small = v;
if(thisTest)
big = v;
else
big = u;
如果我们仔细观察:
int small = (thisTest = u < v) ? u : v;
(thisTest = u < v)
首先被评估。所以如果 u < v
, thisTest = true
否则thisTest = false
.
所以你有:
boolean thisTest = u < v;
int small = thisTest ? u : v; //ternary operator, if thisTest is true then small = u else small = v
big = thisTest ? v : u; //same reason, if thisTest is true, then big = v else big = u
总而言之,small
将包含 u
之间的最小值和v
和big
将包含最大的。如果u == v
, big
和small
将具有相同的值。
您可以了解更多信息here :
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands.
关于Java 按字典顺序比较顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227185/