2012-04-02 68 views
0
public class I { 
     public static void main(String args[]) 
     { 
      int i=0,j=1,k=2; 
      i=i++ - --j + ++k; 
      System.out.println("\ni : "+i+"\nj : "+j+"\nk : "+k); 
     } 
    } 

爲什麼上面的代碼給輸出誰能請給我解釋一下:複雜的表達式的Java

i : 3 
j : 0 
k : 3 

而不是給輸出:

i : 4 
j : 0 
k : 3 

+0

知道了...謝謝大家回答。 – Kameron 2012-04-02 18:02:24

回答

3
  1. 我++ - 給出0(和增量ⅰ)
  2. --j遞減,並給出0
  3. ++ķ增量並給出3
  4. 的0 + 0 + 3的結果被分配給我(這會覆蓋我的值1)。

因此:I:3

1

我猜你的困惑取決於使用i++ - 但i++遞增i的副作用,沒有任何效果,因爲i被重新分配的結果「複雜的表達「。

1

這裏是有問題的生產線生產,請記住,如果i爲0,則i++ == 0++i == 1

i = i++ - --j + ++k; 
i = (0) - (-0) + (3) // i is 3 
1

這是因爲後增量和前增量運營商之間的差異。

前增量出現在變量之前(例如++i),後增量出現在變量之後(例如i++)。

把它分解成更小的部分:

i++ // post increment means increment AFTER we evaluate it 
     // expression evaluates to 0, then increment i by 1 

--j // pre decrement means decrement BEFORE evaluation 
     // j becomes 0, expression evaluates to 0 

++k // pre increment means increment BEFORE evaluation 
     // k becomes 3, expression evaluates to 3 

所以現在我們有:

i = 0 - 0 + 3 // even though i was set to 1, we reassign it here, so it's now 3 
1
  1. 我++給0,然後我變成1
  2. --j使得Ĵ成爲0然後給出0,從步驟1加0給出0
  3. ++ k使k變爲3然後給出3,加上步驟2中的0給出3 ,其被存儲到我

因此,i是3,j是0,k是3

1

i的值是因爲3表達式進行計算這樣的:

i++ //still equals 0 since it's incremented after the evaluation 
- 
--j // equals 0 too since it's decremented is done before the evaluation 
+ 
++k // equals 3 since it's incremented before the evaluation