Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

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

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++) {
        rand.nextInt(1) == 0 ? vertShip(board) : horizShip(board);
    }

My compiler throws me an error stating that the left hand side of the line (rand.nextInt(1) == 0 ) must be a variable. I've tried variants such as

    Random rand = new Random();
    int a = rand.nextInt(1);
    for(int x = 0; x < 3; x++) {
        a == 0 ? vertShip(board) : horizShip(board);
    }

or if statements in the left hand side but they don't fix the problem. Would anyone be able to help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...