为什么我不能使用三元?运算符在两个函数调用之间进行选择 [英] 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);
}
我的编译器抛出一个错误,指出该行的左侧( rand.nextInt(1)== 0)必须是变量。我尝试过变种,例如
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?
推荐答案
并非每个表达都是一个陈述。在此处使用 if
语句。请参阅 14.8表达式声明部分在Java SE 7 Java语言规范中。
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);
你不能做的是:
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.)
这篇关于为什么我不能使用三元?运算符在两个函数调用之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!