為什麼 Java 不允許在這裡使用三元運算符? (Why doesn't Java allow the use of a ternary operator here?)


問題描述

為什麼 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. SchmidtMarc)

參考文件

  1. Why doesn't Java allow the use of a ternary operator here? (CC BY‑SA 2.5/3.0/4.0)

#if-statement #syntax-error #java #conditional-operator






相關問題

Python 和 if 語句 (Python and if statement)

Ruby 一種在條件下執行函數的巧妙方法 (Ruby a clever way to execute a function on a condition)

為什麼我的 php 代碼繞過了一些 if 語句? (Why is my php code bypassing a few if statements?)

為什麼“如果”不是C中的表達式 (Why isn't "if" an expression in C)

如何對此查詢進行選擇案例? (How can I do select case to this query?)

我應該使用方法還是常量標誌? (Should I use methods or constant flags?)

PHP - 使用哪個條件測試? (PHP - Which conditional test to use?)

如果日期較新,則將日期從一個數據幀替換為另一個數據幀 (Replace date from one dataframe to another if it's newer)

BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)

有沒有辦法從 Tableau 中的 regexp_match 語句中排除某些關鍵字? (Is there a way to exclude certain keywords from a regexp_match statement in Tableau?)

Excel 如果單元格為空白單元格總數的空白單元格總數 (Excel If cell is blank sum number of blank cells for a total)

使用另一個數據框的條件創建一個新列 (Create a new column with a condition of another dataframe)







留言討論