Jam*_*dla 3 java ternary-operator
Netbeans说我的三元运算符不是声明.怎么会?
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');
Run Code Online (Sandbox Code Playgroud)
我试过它是if/then/else对应的并且它工作正常:
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');
}
Run Code Online (Sandbox Code Playgroud)
Hov*_*els 14
三元运算符中的语句必须是无效的.他们需要归还一些东西.
System.out.println(direction == 0 ? 'L' : 'R');
Run Code Online (Sandbox Code Playgroud)
三元运算符旨在评估两个表达式中的一个,而不是执行两个语句中的一个.(调用的函数可以是一个表达式,如果函数声明为返回一个值;但是,System.out是PrintStream和PrintStream.print是一个void功能.)您可以用棒if...else结构,你想要做什么,或者你可以这样做:
System.out.print(direction == 0 ? 'L' : 'R');
Run Code Online (Sandbox Code Playgroud)
注意:@iamcreasy的评论指出我对上述内容的处理方式有点不精确.表达式可以评估为空,所以我应该说的是三元运算符评估两个非void表达式中的一个.根据Java语言规范§15.25:
第二个或第三个操作数表达式是void方法的调用是编译时错误.
从JLS部分15.25. Conditional Operator ?:
第二个或第三个操作数表达式是void方法的调用是编译时错误.
这里的第二个和第三个操作数表达式:
direction == 0 ? System.out.print('L') : System.out.print('R');
Run Code Online (Sandbox Code Playgroud)
是void如此,这是一个不三元表达的有效使用.您可以坚持if else使用或使用类似于此替代方案的东西:
System.out.print( direction == 0 ? 'L' : 'R' );
Run Code Online (Sandbox Code Playgroud)
此处的逻辑也不正确:
direction = (int)(Math.random() * 1);
Run Code Online (Sandbox Code Playgroud)
direction将始终评估为0自Math.random()范围内产生的数字[0.0,1.0),这意味着它不包括1.0和铸造double,以int将刚落小数.使用nextInt(2)是一个很好的选择.
| 归档时间: |
|
| 查看次数: |
3247 次 |
| 最近记录: |