2012-12-12 106 views
0

我不得不創建根據一個布爾狀態的輸出像打印語句與運算符? :導致意外的輸出

String smily = null; 
    StringBuffer buff = new StringBuffer(); 
    buff.append(", " + smily == null ? ":)" : ":("); //$NON-NLS-1$ 

    System.out.println(buff.toString()); 

問題是字符串創建語句

", " + smily == null ? ":)" : ":(" 

我在2個不同的蝕環境中測試了它(和可也是2個不同的java版本,這個我沒有檢查),結果是不同的。

結果1:

:(

結果2:

假:(

的CO URSE,如果我加括號,它正在

buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$ 

預期結果:

,:)

可以請人向我解釋,爲什麼Java的解釋聲明辦法?

感謝

+0

提到你的Eclipse的JDK版本 –

+0

哦,差點忘了,StringBuffer的是一種沒有沒有,除非你得到了很充分的理由,StringBuilder的,另一方面是一個是的... – Thihara

回答

4

如果您檢查運算符優先級(請參閱this tutorial),那麼您會注意到加法運算(+)出現在相等前(==)之前。換句話說,在評估相等性之前,Java將首先評估", " + smily =>", null",因此", " + smily == null評估爲false,因此三元運算符評估爲":("

BTW:您可能避免此將它們添加到StringBuffer之前未連接字符串(一個StringBuffer的整點是讓串聯便宜):

String smily = null; 
StringBuffer buff = new StringBuffer(); 
buff.append(", "); 
buff.append(smily == null ? ":)" : ":("); 
3

表達", " + smily == null ? ":)" : ":("被評估爲(", " + smily) == null ? ":)" : ":("

這說明你的結果1.說實話,我不知道爲什麼結果2是可能的。

0
String smily = null; 
StringBuffer buff = new StringBuffer(); 

    if(smily == null){ 
    buff.append(", " + ":)") ; //$NON-NLS-1$ 
    }else{ 
     buff.append(", " + ":(") ; //$NON-NLS-1$ 

} 
+4

他不是在尋找工作,但解釋'可以請有人向我解釋這個。' – amit

1

StringBuffer.append()需要String參數。所以當你把這個沒有括號的時候

buff.append(", " + smily == null ? ":)" : ":(") 

在評估的時候會是", " + null。所以當評估發生時,它總是錯誤的。

至於爲什麼相同的代碼返回兩個結果,我只能假設使用了兩個不同的Java版本,他們處理這種情況的方式不同。

+0

Smily仍然是空的,但實際的比較將是'(「,」+ smily) == null或者'「,null」== null「 –

+0

對我的意思是說不好的措辭......編輯。 – Thihara

0

試試這個..... ................

buff.append(", " + smily == null ? ":)" : ":(");

-在上面的語句你是沒有提及smily == null ? ":)" : ":("要以正確的方式進行評估。

-爲了解決這個問題,你必須使用BODMAS規則,下面是的方式總是評估它已被列入由左到右。

Bracket

Power

Division and Multiplication

Addition and Substraction

-使用支架包圍smily == null ? ":)" : ":("

如:

public class Test { 

    public static void main(String[] args){ 

     String smily = null; 
      StringBuffer buff = new StringBuffer(); 
      buff.append(", " + (smily == null ? ":)" : ":(")); //$NON-NLS-1$ 

      System.out.println(buff.toString()); 
    } 

} 

輸出:, :)