ternary operator not working

♀尐吖头ヾ 提交于 2019-12-28 06:51:26

问题


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');
}

回答1:


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

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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/17635940/ternary-operator-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!