Netbeans is saying that my ternary operator isn't a statement. How come?
int direction;
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1)
direction == 0 ? System.out.print('L') : System.out.print('R');
I tried it's if/then/else counterpart and it works fine:
int direction;
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1)
if(direction == 0){
System.out.print('L');
} else {
System.out.print('R');
}
From the JLS section
15.25. Conditional Operator ?
:both the second and third operand expression here:
are
void
so this is a not a valid use of a ternary expression. You could either stick to theif else
or use something similar to this alternative:Also the logic here is not correct:
direction
will always evaluate to0
sinceMath.random()
generates numbers in the range[0.0,1.0)
which means it does not include1.0
and casting adouble
toint
will just drop the decimals. UsingnextInt(2)
is a good alternative.The statements in the ternary operator need to be non-void. They need to return something.
A ternary operator is intended to evaluate one of two expressions, not to execute one of two statements. (Invoking a function can be an expression if the function is declared to return a value; however,
System.out
is aPrintStream
andPrintStream.print
is avoid
function.) You can either stick with theif...else
structure for what you're trying to do or you can do this:NOTE: The comment by @iamcreasy points out a bit of imprecision in how I phrased things above. An expression can evaluate to nothing, so what I should have said was that a ternary operator evaluates one of two non-
void
expressions. According to the Java Language Specification §15.25: