有人可以告诉我为什么三元运算符的使用不正确吗?操作数 2 和 3 返回一个 boolean 值。
public class Something {
...
private static final double REFERENCE_FRAME_MID_X = 0;
private static final double REFERENCE_FRAME_MID_Y = 0;
private boolean findInsideOrOutsideGeneralEllipse(Point2D destCirclePos) {
List<Boolean> returnValue = new ArrayList<>();
Point2D referenceFrameCenter = new Point2D.Double(REFERENCE_FRAME_MID_X, REFERENCE_FRAME_MID_Y);
Ellipse2D insideAreaEllipse2D = getEllipse2D(referenceFrameCenter.getX(), referenceFrameCenter.getY(),
destCirclePos.distance(referenceFrameCenter));
// doesn't work
insideAreaEllipse2D.contains(destCirclePos) ? returnValue.add(true) : returnValue.add(false);
// works
if (insideAreaEllipse2D.contains(destCirclePos)) {
returnValue.add(true);
} else {
returnValue.add(false);
}
}
...
}
最佳答案
Java 三元运算条件的用法应该如下所示
result = testCondition ? value1 : value2
这是java语言规范。
Equality, Relational, and Conditional Operators
In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result
关于Java 三元运算符 (? :) doesn't work; second or third operand return boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19010399/