Java – ternary operator does not work
•
Java
NetBeans says my ternary operator is not a declaration How?
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've tried that it corresponds to if / then / else and it works properly:
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');
}
Solution
Statements in ternary operators must be invalid They need to return something
System.out.println(direction == 0 ? 'L' : 'R');
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
