2013-06-18 124 views
-1
import java.math.BigInteger; 
import java.util.Arrays; 
import java.util.Scanner; 

public class Java { 

    public static int numberOfLoops; 
    public static int numberOfIterations; 
    public static int[] loops; 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     System.out.print("N = "); 
     numberOfLoops = input.nextInt(); 

     System.out.print("K = "); 
     numberOfIterations = input.nextInt(); 

     input.close(); 

     loops = new int[numberOfLoops]; 
     System.out.println("main START"); 
     nestedLoops(0); 
     System.out.println("main END"); 
    } 

    public static void nestedLoops(int currentLoop) { 
     System.out.println("nestedLoops"); 
     System.out.println("currentLoop " + currentLoop); 
     if (currentLoop == numberOfLoops) { 
      printLoops(); 
      return; 
     } 

     for (int counter = 1; counter <= numberOfIterations; counter++) { 
      System.out.println("nestedLoops in LOOP"); 
      System.out.println("currentLoop in LOOP " + currentLoop); 
      loops[currentLoop] = counter; 
      nestedLoops(currentLoop + 1); 

     } 
    } 

    public static void printLoops() { 
     System.out.println("printLoops"); 
     for (int i = 0; i < numberOfLoops; i++) { 
      System.out.printf("%d", loops[i]); 
     } 
     System.out.println(); 
    } 

} 

大家好。我是新來的,這是我的第一篇文章。調試一步一步遞歸

我的問題是:

如果我把爲N = 2和K = 4,爲什麼後首次返回currentLoop繼續1中,我們傳遞給方法0?

感謝,尼古拉

+0

我不明白.. – Maroun

+0

請更明確地詢問你在問什麼。即說明你期望在哪裏發生,然後告訴我們你的想法實際發生了什麼,以及爲什麼這不符合你的期望。 –

回答

1

我不知道如果我理解你的completely..but

問題當你調用

nestedLoops(0); 

你去與currentLoop = 0的nestedLoops功能。 在此功能中,您可致電

nestedLoops(currentLoop + 1); 

這就是爲什麼你會得到一個

nestedLoop(1) 

叫當你在你的

nestedLoop(0) 

是讓我知道如果我誤解你的問題。


編輯:

nestedLoops(1) 

被調用時,我們稱之爲

nestedLoops(2) 

吧? 當我們比較currentLoop和內部nestedLoops的numberOfLoops(2),它們都是2, 所以我們進入

printLoops(); 

一旦printLoops完成後,我們返回到

nestedLoops(2) 

然而,printLoops後(),我們有一個

return; 

因此,我們回到了的

nestedLoops(2) 和我們回來到

nestedLoops(1) 

其中nestedLoops(2)從調用。

這有道理嗎?

+0

感謝您的快速回答!我們不明白什麼時候我們去遞歸的底部 if(currentLoop(2)==(2)numberOfLoops){printLoops(); return; } 我們又回到了for循環和變量currentLoop是1 –

+0

@ user2498774檢查我的編輯! – Calpis

+0

現在我明白了。謝謝! –