2013-07-14 107 views
3

Netbeans說我的三元運營商不是一個聲明。怎麼來的?三元運營商不工作

int direction; 
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1) 
direction == 0 ? System.out.print('L') : System.out.print('R'); 

我想它的if/then/else語句對應,它工作正常:

int direction; 
direction = (Math.random() < 0.5) ? 0 : 1; // direction is either L or R (0 or 1) 
if(direction == 0){ 
    System.out.print('L'); 
} else { 
    System.out.print('R'); 
} 
+1

在Java中,0沒有布爾表示。只有布爾表達式可用於此。 – Kon

+0

[爲什麼這個方法不工作? Java三元運算符](http://stackoverflow.com/questions/16876698/why-doesnt-this-method-work-java-ternary-operator) –

回答

12

在三元運算符的語句必須非空。他們需要回報一些東西。

System.out.println(direction == 0 ? 'L' : 'R'); 
+0

ahhh這太棒了。謝謝。 –

+0

@庫德拉69:不客氣! –

9

三元運算符旨在評估兩個表達式中的一個,不執行兩個語句之一。 (如果函數被聲明爲返回值,則調用函數可能是一個表達式;但是,System.outPrintStreamPrintStream.printvoid函數。)您可以使用if...else結構來實現您正在嘗試執行的操作,或者您可以這樣做:

System.out.print(direction == 0 ? 'L' : 'R'); 

注意:@iamcreasy的評論指出了我在上述措辭中的不精確性。表達式可以評估爲無,因此我應該說的是,三元運算符評估兩個表達式中的一個。根據Java Language Specification §15.25

它是第二或第三操作數 表達編譯時誤差爲空隙方法的調用。

+0

+1,用於獲取詳細信息。 –

+1

但根據[JLS 14.8](https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.8)MethodInvocation是表達式聲明。那麼這是否意味着一個表達式可以返回void? (在一般情況下) –

+0

@iamcreasy - 表達式確實可以是無效的(我不會使用「return void」,因爲「return」在JLS中具有特定的技術含義),但不是在一般情況下。根據[JLS§15.1] (https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.1),評估表達式的結果可以是一個變量(類似於C中的_lvalue_) ,一個值,或者什麼也不是(一個空表達式)。然而,void表達式_「只能用作表達式語句(第14.8節),因爲表達式可能出現的每個其他上下文都需要表達式來表示某些東西。」_ –

5

從JLS部15.25. Conditional Operator ?

它是第二或第三操作數表達是一個空隙方法的調用一個編譯時間錯誤。

第二和第三操作數的表達這裏:

direction == 0 ? System.out.print('L') : System.out.print('R'); 

void所以這是一個不三元表達的有效使用。你既可以堅持if else,或者使用類似的東西,這種替代:

System.out.print(direction == 0 ? 'L' : 'R'); 

而且這裏的邏輯是不正確的:

direction = (int)(Math.random() * 1); 

direction將始終評估爲0因爲Math.random()範圍內產生數[0.0,1.0)這意味着它不包括1.0和鑄doubleint將只是drop the decimals。使用nextInt(2)是一個很好的選擇。

+0

+1「的Math.random()'。 OP應該使用'Math.random()* 2'或創建一個'java.util.Random'對象並使用'nextInt(2)'。 –

+0

是的,實際上我在測試程序後立即就發現了這個問題。將其改爲direction =(Math.random()<0.5)? 0:1; –