Question

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');
}
Was it helpful?

Solution

The statements in the ternary operator need to be non-void. They need to return something.

System.out.println(direction == 0 ? 'L' : 'R');

OTHER TIPS

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 a PrintStream and PrintStream.print is a void function.) You can either stick with the if...else structure for what you're trying to do or you can do this:

System.out.print(direction == 0 ? 'L' : 'R');

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:

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

From the JLS section 15.25. Conditional Operator ?:

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

both the second and third operand expression here:

direction == 0 ? System.out.print('L') : System.out.print('R');

are void so this is a not a valid use of a ternary expression. You could either stick to the if else or use something similar to this alternative:

System.out.print( direction == 0 ? 'L' : 'R' );

Also the logic here is not correct:

direction = (int)(Math.random() * 1);

direction will always evaluate to 0 since Math.random() generates numbers in the range [0.0,1.0) which means it does not include 1.0 and casting a double to int will just drop the decimals. Using nextInt(2) is a good alternative.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top