【发布时间】:2016-06-18 21:59:25
【问题描述】:
我运行了一个三元运算符的简单示例。我想知道为什么在第二种情况下它不起作用。
class Gun
{
public int hit;
}
public class Test1 {
public static void main(String[] args) {
Gun weapon1=new Gun();
weapon1.hit=54;
String es1=new String("You killed him!. Grac!");
String es2=new String("Ops, you were noticed.");
System.out.println((weapon1.hit>50 ? es1 : es2)); //this works fine
weapon1.hit>50 ? System.out.println(es1) : System.out.println(es2); // this doesn't
}
}
毕竟,三元运算符的工作原理应该类似于 if-else 语句,而这个 if-else 代码工作得很好:
if (weapon1.hit>50)
System.out.println(es1);
else
System.out.println(es2);
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - not a statement at Test1.main(Test1.java:39) 如果我取消注释 weapon1.hit>50 ? System.out.println(es1) : System.out.println(es2); 行,这就是我得到的错误。
【问题讨论】:
-
System.out.println(weapon1.hit > 50 ? es1 : es2);。此外,请了解如何格式化您的代码(只需使用 IDE;它会为您完成)以保持我们的理智。 -
“不起作用”是指它无法编译?就像分成 3 行的字符串文字不会编译?因为,您知道,“不起作用” 是对问题的糟糕描述,如果您遇到错误,您应该向我们展示错误,因此我们可以确定您在说什么.
-
@Pshemo 所以您决定静默修复该代码中至少 3 个编译错误之一?
-
@parsecer 将您的错误粘贴到不在此处的问题中
-
@parsecer 你得到这个错误是因为三元运算符是一个表达式,而不是一个语句。
标签: java