0
我的計劃是想打印的遞歸調用我把這樣的數字:爲什麼我打印的呼叫數量遞歸在Java中以這種特殊的方式錯了嗎?
例如:撥打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 4.
This ALSO written by call number 3.
This ALSO written by call number 2.
This ALSO written by call number 1.
縮進的假設是這樣的了。
我的代碼會產生這樣的事情,而不是:
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.
This was written by call number 2.
This was written by call number 3.
This was written by call number 4.
它假設是從我所看到的簡單的,但我的輸出,否則說。
我的代碼,而無需主要方法和構造函數(它們不會影響任何東西),我沒有刪除卻把也是String類型,在前面的空間:
import java.util.*;
public class callNumber
{
Queue intStack = new LinkedList(); // stores call numbers for printing second string
private String st1 = "This was written by call number ";
private String st2 = "This ALSO written by call number ";
int i = 2;
public void callingNum(int num)
{
intStack.add(num);
i = num;
if(num >= 2)
{
callingNum(num - 1);
System.out.println(st1 + num + ".");
st1 = " " + st1;
st2 = " " + st2;
}
if(i == num)
{
while(!intStack.isEmpty())
{
System.out.println(st2 + intStack.remove() + ".");
st2.replaceAll(" ", "");
}
}
i++;
}
'新的String(「‘)'等同於'’」',除了它在堆上創建額外的對象。不要這樣做。 – shmosel
@shmosel我修好了。 – Eap123
'而(!intStack.isEmpty())'將清空隊列中的第一次調用完成,這隻要'num'達到1發生。 – teppic