后期和预增量运算符OCJA-1.8

时间:2017-11-06 17:40:52

标签: java operators post-increment pre-increment unary-operator

我正在练习java post和pre increment operator,我很难理解下面程序的输出。如何生成输出为" 8" ?

public class Test{

public static void main(String [] args){
    int x=0;
    x=++x + x++ + x++ + ++x;
    System.out.println(x);
   }    
}

我已经尝试了一些示例程序,我可以跟踪输出

public class Test{
 public static void main(String [] args){
    int x=0;
    x=++x + ++x + ++x + x++;
    //  1 + 2 + 3 + 3 =>9
    System.out.println(x);
  } 
}

2 个答案:

答案 0 :(得分:2)

这可以说与以下相同:

public static void main(String[] args) {
    int x=0;
    int t1 = ++x;
    System.out.println(t1);//t1 = 1 and x = 1
    int t2 = x++;
    System.out.println(t2);//t2 = 1 and x = 2
    int t3 = x++;
    System.out.println(t3);//t3 = 2 and x = 3
    int t4 = ++x;
    System.out.println(t4);//t4 = 4 and x = 4

    x= t1 + t2 + t3 + t4;//x = 1 + 1 + 2 + 4
    System.out.println(x);//8
}

答案 1 :(得分:1)

这可能有助于理解运营商的前后行为。

 public class Test{

    public static void main(String [] args){
        int x=0;
        x =   ++x   +  x++   +      x++  +     ++ x;
      //0 = (+1+0)  + (1)    + (+1 +1)   + (+1 +1 +2);
      //0  = 1      + 1      +  2      +  4
         System.out.println(x); // prints 8.
       }    
    }
相关问题