【发布时间】:2014-05-10 12:13:11
【问题描述】:
我目前正在从一本书中学习 Java 的基础知识,并且我将这段代码作为使用递归的嵌套循环的示例。我什么都懂,但代码末尾的返回函数的用法。我无法弄清楚程序是如何决定的,何时在 K=4 时准确停止。我试图调试它,这对我来说仍然是个谜。这是代码:
import java.util.Scanner;
public class nestedLoops {
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];
nestedLoops(0);
}
public static void nestedLoops(int currentLoop) {
if (currentLoop == numberOfLoops) {
printLoops();
return;
}
for (int counter=1;counter<=numberOfIterations;counter++) {
loops[currentLoop] = counter;
nestedLoops(currentLoop + 1);
}
}
public static void printLoops() {
for (int i = 0; i < numberOfLoops; i++) {
System.out.printf("%d ", loops[i]);
}
System.out.println();
}
}
如果有人向我解释 return 在这个特定示例中最终在数字为“4.4”时的工作原理以及它在 void 方法中的工作原理,那将非常有帮助,因为我一直在寻找对此的解释但没有成功……
先谢谢你!
【问题讨论】:
-
在使用return语句的void方法中,方法将结束。
-
对,我知道这一点。但是,如果您调试此代码,您会发现它多次将值“currentLoop”更改为 2,而不是在特定时刻程序决定它将是最后一次,实际上给出了答案,我不明白它是如何实现的......
标签: java recursion return void