[英]Return function in void method when using Recursion
我目前正在从一本书中学习 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();
}
}
如果有人向我解释当数字为“4.4”时 return 在这个特定示例中的最终工作原理以及它在 void 方法中的工作原理,那将非常有帮助,因为我一直在寻找对此的解释,但没有成功...
先谢谢了!
nestedLoops
方法中的 for 循环调用自身numberOfIterations
次。 所以它变为 0,然后进行numberOfIterations
调用。 因此,如果您输入 4,您会看到 4 个调用 currentLoop=1 然后 16 个调用 currentLoop=2 等等......
当所有其他方法都失败时,编写一些代码来调试您的代码。 我自己是一个视觉人士,所以当调试器为我做一些输出时,输出会有所帮助。
public static HashMap<Integer, Integer> map = new HashMap();
public static void main(String[] args) {
....
System.out.println(map);
}
public static void nestedLoops(int currentLoop) {
if(map.containsKey(currentLoop)) {
map.put(currentLoop, map.get(currentLoop)+1);
} else {
map.put(currentLoop, 1);
}
...
}
void
方法中的 return 语句停止运行该方法并返回到调用代码。 在这个例子中,输入:
numberOfLoops = 4
numberOfIterations = 4
获取输入后,您立即根据输入创建一个数组,然后调用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);
}
}
说明
首先,让我们忽略 for 循环。 if 语句检查是否currentLoop == numberOfLoops
并且每次调用此方法时都会执行此操作。 现在currentLoop
是 0(我们在调用它时传递给这个方法的值)和 numberOfLoops 是 4(我们在最开始输入的值)所以这是假的,里面的代码都没有被调用。
if 语句下面的 for 循环将运行numberOfIterations
次。 在我们的例子中,这个循环将运行 4 次。 我将按顺序写出下面发生的事情:
- input is 4, 4
- nestedLoops(0) called- currentLoop = 0
- if evaluates to false
- for loop runs
- loops[0] = 1
- nestedLoops(1)
- if evaluates to false ( 1 != 4)
- for loop runs
- loops[1] = 1
- nestedLoops(2)
- if evaluates to false (2 != 4)
- for loop runs
- loops[2] = 1
- nestedLoops(3)
- if evaluates to false (3 != 4)
- for loop runs
- loops[3] = 1
- nestedLoops(4)
- if evaluates to TRUE (4 == 4)
- loops are printed (all values are 1 right now)
-returns to calling location
-Which is the for loop associated with this indention.
-For loop increments, and then sets loops[3] = 2.
- then this loop finishes
- then this loop finishes
etc. etc.
void 方法中的 return 仅表示“好吧,停止你正在做的事情,回到谁/什么人那里并继续前进”在这种情况下,它跳回前一个 for 循环以继续工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.