簡體   English   中英

后期和預增量操作員OCJA-1.8

[英]Post and Pre Increment Operator OCJA-1.8

我正在練習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);
  } 
}

這可以說與以下相同:

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
}

這可能有助於理解運營商的前后行為。

 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.
       }    
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM