2012-12-19 32 views
7

這是我的代碼:的println不打印預期值

public static void main(String[] arg) 
{ 

    String x = null; 
    String y = "10"; 
    String z = "20"; 

    System.out.println("This my first out put "+x==null?y:z); 

    x = "15"; 

    System.out.println("This my second out put "+x==null?y:z); 

} 

我的輸出是:

20 
20 

但我很期待這樣的:

This my first out put 10 
This my second out put 20 

有人能解釋我爲什麼爲這兩個println調用輸出「20」作爲輸出?

+0

Sumit Singh的回答解釋了爲什麼輸出是這樣的。原因是運算符優先級,請參閱[本文檔](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) – jlordo

+0

@coders我接受 – Suranga

回答

9

System.out.println("This my first out put "+x==null?y:z);會像

("This my first out put "+x)==null?y:z它永遠不會是真正的執行。所以,它會顯示z的值。

例如:

int x=10; 
int y=20; 
System.out.println(" "+x+y); //display 1020 
System.out.println(x+y+" "); //display 30 

對於上述情況下,操作進行左至右

正如,你說,你期待這樣的:

This my first output 10 

對於這一點,你需要在你的代碼變化不大。試試這個

System.out.println("This my first output " + ((x == null) ? y : z));

+1

對Java中表達式的評估並不總是保持不變。它考慮到運營商的優先權! –

+0

@StephenC我知道,但我只是在談論這種情況。相反,它會增加更多的困惑,我從我的聲明中刪除了總是。我相信,現在會沒事的。 :) – Ravi

4

嘗試

System.out.println("This my first out put "+ (x==null?y:z)); 
+2

這確實會生成所需的輸出,但會不回答OP問題:_請有人解釋我**爲什麼**我爲println調用獲得「20」作爲輸出?_ – jlordo

1

你需要嘗試:

System.out.println("This my first out put "+(x==null?y:z)); 
x = "15"; 
System.out.println("This my second out put "+(x==null?y:z)); 
2

使用下面的代碼,這將解決你的問題:萬阿英,蔣達清是因爲其採取 -

System.out.println(("This my first out put "+x==null?y:z); 

由於

System.out.println(("This my first out put "+x)==null?y:z);

public static void main(String[] arg) 
{ 

    String x = null; 
    String y = "10"; 
    String z = "20"; 

    System.out.println("This my first out put "+(x==null?y:z)); 

    x = "15"; 

    System.out.println("This my second out put "+(x==null?y:z)); 

} 
+0

+1,首先回答真正的問題,**爲什麼**輸出是這樣的。 – jlordo