【发布时间】:2020-09-22 18:50:06
【问题描述】:
我正在尝试使用递归来打印出两行文本,并且每次出现递归时都会缩进(下面的 javadoc 中的示例)。我知道使用(numCalls + 1) 将允许它每次都增加缩进,但我不确定如何实际将它放在一起,所以它要求的也是。
public class Practice1 {
/**
* Prints 2 lines of text for each recursive call, indicating call number
* (a value >= 1, and <= value of numCalls, as illustrated below. Each
* level of recursion should be indicated by indenting the input line by
* r spaces. For example, if numCalls is 3, the method should print:
* call 1
* call 2
* call 3
* back 3
* back 2
* back 1
* @param r the level of method calls
* @param numCalls the number of intended levels
*/
public static void stairSteps(int r, int numCalls) {
if (r == 0) {
System.out.println("Done");
} else {
System.out.println("call " + r);
System.out.println("back " + r);
r--;
numCalls++;
stairSteps(r, numCalls);
}
}
【问题讨论】: