三元运算符不工作

三元运算符不工作

本文介绍了三元运算符不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Netbeans说我的三元运算符不是声明。怎么会?

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

我试过if / then / else对应它并且运行正常:

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 statements in the ternary operator need to be non-void. They need to return something.

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

这篇关于三元运算符不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:24