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');
}
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary. You can write the above program in just 3 lines of code using a ternary operator.
We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");
The alternative to the ternary operation is to use the && (AND) operation. Because the AND operator will short-circuit if the left-operand is falsey, it acts identically to the first part of the ternary operator.
The statements in the ternary operator need to be non-void. They need to return something.
System.out.println(direction == 0 ? 'L' : 'R');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With