英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论