2012-04-02 83 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