Java中的前后增量和减量

时间:2015-03-18 12:45:16

标签: java post increment pre decrement

后天是我的计算机考试(JAVA),我在上面的标题中遇到了很大的问题。我明白post和pre增量和减量意味着什么。但是,当事情发生在复杂而冗长的陈述中时,我无法理解该怎么做。这个问题的一个例子如下。

class java_1
{ 
  public void main()
{
int x = 4;
x += x++ - --x + x + x--;
}
}

你看到复杂陈述的含义。该语句只包含一个连续递增和递减的变量,我在这里感到困惑。你能帮我解决一下我的困惑吗?另外,请给出上述代码的答案。

1 个答案:

答案 0 :(得分:3)

a += b;a = a + b类似。使用这个假设我们可以重写

x += x++ - --x + x + x--;

as

x = x + (x++ - --x + x + x--);

现在让我们x = 4并评估右侧(从左到右)

x + (x++ - --x + x + x--) 

4 + (x++ - --x + x + x--) 
^                         //still x = 4

4 + (4 - --x + x + x--)   
     ^                    //x++ use current value (4), then increment x to 5

4 + (4 - 4 + x + x--)
         ^                //--x decremented to 4, then use current value (4)

4 + (4 - 4 + 4 + x--)     
             ^            //still x = 4

4 + (4 - 4 + 4 + 4)       
                 ^        //x-- read current value (4), then decrement x to 3

所以我们得到了

x = 4 + (4 - 4 + 4 + 4);

表示

x = 12;
相关问题