這是學校的作業。我無法理解我怎麼可以打印遞歸如下:以間距遞歸地打印文字
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 4.
This ALSO written by call number 3.
This ALSO written by call number 2.
This ALSO written by call number 1.
我不知道我是否應該是說明循環與遞歸或是否有遞歸打印所有的這一種方式。此外,我將如何去逆轉遞歸調用,以便從示例輸出的4開始?
這是我目前的輸出。
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
This ALSO written by call number 1.
This ALSO written by call number 2.
This ALSO written by call number 3.
This ALSO written by call number 4.
沒有在執行for循環B/C我不知道如果這部分也應該是遞歸的間距。
我的代碼:
public class Recursion {
public static void main(String[] args) {
for (int i = 2; i < 5; i++) {
System.out.println("This was written by call number " + i + ".");
}
recurse(4);
}
public static void recurse(int n) {
String temp = "";
for (int i = 0; i < n; i++) {
temp += " ";
}
if (n < 2) {
System.out.println("This ALSO written by call number " + n + ".");
}
else {
recurse(n - 1);
System.out.println(temp + "This ALSO written by call number " + n + ".");
}
}
爲了使它更容易,我建議使用2個獨特的功能。一個在遞歸調用後打印,另一個在前面打印。 – bestsss 2014-10-31 23:38:02
@MichaelJames不,不需要使用2個函數。我正在編寫一個答案...... – ajb 2014-10-31 23:48:17
你可以用一個函數來完成它,然後可能需要硬編碼4,或者將它作爲第二個參數。通常我會寫遞歸計數 - 只需要一個函數來增加計數器。無論哪種方式,遞歸函數都是大約4行代碼。 – bestsss 2014-10-31 23:48:58