英文:
Why doesn't Java allow the use of a ternary operator here?
问题
以下是翻译好的内容:
代替键入:
if (Math.random() < .5) {
System.out.println("toto");
} else {
System.out.println("tata");
}
我认为,将其改为以下方式会更有用和合乎逻辑:
Math.random() < .5 ? System.out.println("toto") : System.out.println("tata");
然而,我遇到了“not a statement”错误。我不明白为什么会出现这个问题。
英文:
Instead of typing :
if (Math.random() < .5) {
System.out.println("toto");
} else {
System.out.println("tata");
}
I would find it useful, and logical, to type instead :
Math.random() < .5 ? System.out.println("toto") : System.out.println("tata");
However, I get the error not a statement
. I don't understand how this is an issue.
答案1
得分: 2
因为三元运算符会将一个值赋给一个变量。将其改为:
String toPrint = Math.random() < 0.5 ? "toto" : "tata";
System.out.println(toPrint);
英文:
Because the ternary operator assigns a value to a variable. Change it to:
String toPrint = Math.random() < .5 ? "toto" : "tata";
System.out.println(toPrint);
专注分享java语言的经验与见解,让所有开发者获益!
评论