Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ternary operator not working

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');
}
like image 595
Jamie Kudla Avatar asked Jul 14 '13 02:07

Jamie Kudla


People also ask

How do you handle 3 conditions in a ternary operator?

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.

How do you solve a ternary operator?

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.

How the ternary operator works in C?

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");

What can I use instead of a ternary operator?

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.


2 Answers

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

System.out.println(direction == 0 ? 'L' : 'R');
like image 139
Hovercraft Full Of Eels Avatar answered Oct 23 '22 17:10

Hovercraft Full Of Eels


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.

like image 9
Ted Hopp Avatar answered Oct 23 '22 17:10

Ted Hopp