Java ternary operator (?:) doesn't work; second or third operand return boolean

我是研究僧i 提交于 2019-11-26 18:36:41

问题


Can someone tell me why this use of the ternary operator is incorrect? Operands 2 and 3 return a 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);
    }
}
...
}

回答1:


Usage of Java ternary operation condition should looks like

result = testCondition ? value1 : value2

it's java-language specification.

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




回答2:


From JLS - Conditional Operator:

In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.

Grammar of expression statements from JLS - 14.8:

Certain kinds of expressions may be used as statements by following them with semicolons:

ExpressionStatement:
      StatementExpression ;

StatementExpression:
       Assignment
       PreIncrementExpression
       PreDecrementExpression
       PostIncrementExpression
       PostDecrementExpression
       MethodInvocation
       ClassInstanceCreationExpression

An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.

Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements.

Now the way you are using the conditional operator is not a valid expression statement, as inferred from it's grammar. And hence you get the compiler error. You have to use it in any of the above mentioned context.



来源:https://stackoverflow.com/questions/19010399/java-ternary-operator-doesnt-work-second-or-third-operand-return-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!