2013-08-30 80 views
0

感到困惑與輸出(即後在MnoshowValue法)方法調用輸出混亂

class Lab2 { 
    public static void main(String[] aa) { 
     int ab=98; 
     System.out.println("ab in main before\t:"+ab); 
     Mno ref = new Mno(); 
     ref.showValue(ab); 

     System.out.println("ab in Main After\t:"+ab); 
    } 
} 

class Mno { 
    void showValue(int ab) { 
     System.out.println("ab in showvalue before\t:"+ab); 
     if (ab!=0) 
      showValue(ab/10); 
     System.out.println("ab in showvalue After\t:"+ab); 
    } 
} 

我得到了下面的輸出...它是如何0,9,98後打印顯示的值。 ...?

F:\Train\oops>java Lab2 
ab in main before  :98 
ab in showvalue before :98 
ab in showvalue before :9 
ab in showvalue before :0 
ab in showvalue After :0 
ab in showvalue After :9 
ab in showvalue After :98 
ab in Main After  :98 
+0

Java通過副本傳遞,而不是通過引用 – nachokk

回答

2

在Java中,變量的唯一副本在方法調用期間傳遞。

在基元的情況下,它的值的副本,並在對象的情況下,它的對象的引用的副本。

因此,當您將副本傳遞給showValue方法時,main方法中int ab的值不會更改。

0

您在這裏進行遞歸調用:

ab in showvalue before :98 
showValue(98); 
ab in showvalue before :9 
-> showValue(9); 
    ab in showvalue before :0 
    -> showValue(0); //if returns true here, so no more recursive call 
    ab in showvalue after :0 
ab in showvalue after :9 
ab in showvalue before :98 
+0

感謝你GV,實際上我沒有正確理解代碼,「shovalue after」語句在showvalue()方法裏面 – Robo

0

你每一次ab!=0,遞歸調用函數showValue其中,再加上Java正在傳遞的ab副本的事實,導致在你的輸出出現金字塔形式。

所有的ab in showvalue before輸出都是在您自己調用函數時產生的,每次都會傳遞ab的副本。看到ab的值從未真正改變過,一旦所有的showValue調用都被評估過,循環會以相反的順序解開並打印舊的副本。

0

它是一個遞歸調用。程序的控制返回到它以不同的值調用它自己的點。 請參閱您的呼叫 - >

ShowValue(98) - > ShowValue(9) - > ShowValue(0)

明白了嗎?