逐步调试逐步调试

时间:2013-06-18 21:04:04

标签: java recursion

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?

谢谢,尼古拉

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解你的问题。但是

致电时

nestedLoops(0);

您使用currentLoop = 0进入nestedLoops函数。 在此功能中,您可以调用

nestedLoops(currentLoop + 1);

这就是你得到

的原因
nestedLoop(1) 
当你在

时,

被叫

nestedLoop(0) 

如果我误解了你的问题,请告诉我。


编辑:

何时

nestedLoops(1) 
调用

,我们调用

nestedLoops(2)

正确? 当我们比较nestedLoops(2)中的currentLoop和numberOfLoops时,它们都是2, 所以我们进入

printLoops();

printLoops完成后,我们将返回

nestedLoops(2)

然而,在printLoops()之后,我们有一个

return;

因此,我们退出

nestedLoops(2) 我们回到

nestedLoops(1)

从中调用nestedLoops(2)。

这有意义吗?