問題描述
為什麼 Java 不允許在這裡使用三元運算符? (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
代碼>。我不明白這是怎麼回事。
參考解法
方法 1:
Because the ternary operator assigns a value to a variable. Change it to:
String toPrint = Math.random() < .5 ? "toto" : "tata";
System.out.println(toPrint);
(by J. Schmidt、Marc)
參考文件