Java vs C中的三元运算符 [英] Ternary operator in java vs c
问题描述
为什么这个三元运算符不能在这里工作,但是在c中什么地方可以正常工作?
Why does this ternary operator doesn't works over here but where as in c it works perfectly?
import java.util.Scanner;
class Pack {
public static void main(String[] args) {
System.out.println("enter a number");
Scanner s=new Scanner(System.in);
int i=s.nextInt();
i%2==0?System.out.println("even"):System.out.println("odd");
}
}
推荐答案
因为您不能在Java中分配类似的语句。如果您像使用三元组,那么您的三元组将正常工作。
Because you can't assign a statement like that in Java. Your ternary would work if you used it like,
System.out.println(i%2==0 ? "even" : "odd");
从根本上讲,Java不是C。
Fundamentally, Java isn't C.
编辑
您在评论中问,我在哪里分配了什么东西?
另一个条件运算符是
?:
,可以认为是if-then-else语句的简写(在本课程的控制流语句部分中进行了讨论)。此运算符也称为三元运算符,因为它使用三个操作数。在下面的示例中,该运算符应读取为:如果someCondition
为true
,则分配值value1
到value
的值;否则,分配value2
到结果
。
Another conditional operator is
?:
, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "IfsomeCondition
istrue
, assign the value ofvalue1
toresult
. Otherwise, assign the value ofvalue2
toresult
."
进一步,第15章表达式-条件运算符? :
(JLS-15.25)说
Further, Chapter 15. Expressions - Conditional Operator ? :
(JLS-15.25) says
这是一个编译时错误第二个或第三个操作数表达式是
void
方法的调用。
这篇关于Java vs C中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!