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?
Not every expression is a statement. Use an
ifstatement here. See Section 14.8 Expression Statements in the Java SE 7 Java Language Specification.Examples of expression statement for each of the above:
What you can’t do is:
However, if you’re dead set on obfuscating your code, I guess you could write:
(I think. I don’t have a compiler to hand and wouldn’t usually write such code.)