Why can't I use the ternary ? operator to select between two function calls?

后端 未结 4 1365
悲哀的现实
悲哀的现实 2020-12-03 23:24

I was recently programming and ran into an issue using the ? : operand. Here\'s my code.

    Random rand = new Random();
    for(int x = 0; x < 3; x++) {
         


        
相关标签:
4条回答
  • 2020-12-03 23:50

    The compiler is right. The ternary operator returns something, so you need to assign it to a variable.

    0 讨论(0)
  • 2020-12-04 00:05

    Not every expression is a statement. Use an if statement here. See Section 14.8 Expression Statements in the Java SE 7 Java Language Specification.

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

    ExpressionStatement:
        StatementExpression ;
    
    StatementExpression:
        Assignment
        PreIncrementExpression
        PreDecrementExpression
        PostIncrementExpression
        PostDecrementExpression
        MethodInvocation
        ClassInstanceCreationExpression
    

    Examples of expression statement for each of the above:

    x = y;
    ++x;
    --x
    x++;
    x--;
    fn(); // Or donkey.fn();, etc.
    new Donkey(this);
    

    What you can't do is:

    b ? f() : g();
    f() + g();
    

    However, if you're dead set on obfuscating your code, I guess you could write:

    fn(a == 0 ? vertShip(board) : horizShip(board));
    (a == 0 ? vertShip(board) : horizShip(board)).fn();
    

    (I think. I don't have a compiler to hand and wouldn't usually write such code.)

    0 讨论(0)
  • 2020-12-04 00:09

    Java isn't perl. Use an if statement:

     if (rand.nextInt(1) == 0) {
        vertShip(board);
     } else { 
        horizShip(board);
     }
    

    You can't build a function call statement by sticking the ternary ? on the front.

    0 讨论(0)
  • 2020-12-04 00:13
    a == 0 ? vertShip(board) : horizShip(board); // is an expression
    if (a == 0) vertShip(board); else horizShip(board); // is a statement
    

    Compare:

    if (condition) 
    {
        execute statement(s)
    }
    else
    {
        execute statement(s)
    }
    

    With:

     expression1 ? expression2 : expression3 
    

    Use the appropriate construct.

    0 讨论(0)
提交回复
热议问题