2017-07-30 26 views
-3

我試圖理解這種遞歸方法,但我感到困惑。不同調用的Java遞歸方法 - 難以遵循的變量值

輸出是: X:3 X:4 X:3 Y:4

我終於明白了這一步:在第一個x:3被打印出來,因爲我們通過數字3和4.然後它再次用x-1,y調用該方法。但職位交換。請解釋第二次方法調用後x和y的值在不同的點上以及它們在每次調用後如何改變。謝謝。

public class Test { 

     public static void obscure (int x, int y){ 

     if (x * y <= 4){ 
      return; 
     } 
     System.out.println("x: " + x); // X ist 4 

     if (x >= y){ 
      obscure(x-1, y); 
     }else{ 
      obscure(y,x-1); 
      System.out.println("y: " + y); 
    } 
} 

    public static void main(String[] args){ 
    obscure(3,4); 
    } 
} 
+0

使用調試器。 –

+0

'但是職位交換'這是正確的。 '如果(x> = y){' - 'x'這裏是'3','y'是'4'。它轉到'else'塊,將'y'作爲第一個參數,將'x-1'作爲第二個參數。 – BackSlash

+1

歡迎來到Stack Overflow!它看起來像你需要學習使用調試器。請幫助一些[互補調試技術](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之後仍然遇到問題,請隨時回答一個更具體的問題。 –

回答

1

在此代碼會發生什麼:

first call: obscure(3,4) //x=3,y=4 
    output: x:3 
    else clause (not x(3) >= y(4)) 
     second call: obscure (4,2) //x=4,y=2 
      output: x:4 
      if clause (x(4) >= y(2) 
       third call: obscure(3,2) //x=3,y=2 
        output: x:3 
        if clause (x(3) >= y(2)) 
         fourth call: obscure(2,2) //x=2, y=2 
          x(2)*y(2) <= 4 //returns 
         end of fourth call 
       end of third call 
     end of second call 
     output in else clause of first call: y:4 
end of first call