2016-11-22 43 views
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++; 
} 
+1

'新的String(「‘)'等同於'’」',除了它在堆上創建額外的對象。不要這樣做。 – shmosel

+0

@shmosel我修好了。 – Eap123

+0

'而(!intStack.isEmpty())'將清空隊列中的第一次調用完成,這隻要'num'達到1發生。 – teppic

回答

0

首先,你的序列打印和通話是錯誤的;這就是爲什麼你會違規排隊。這項任務說明了差異。您的基本順序必須是:

print "was written" line 
recur with N-1 
print "ALSO written" line 

您已經顛倒了前兩個步驟,這是您的行順序錯誤的原因之一。

intStack;這會導致你各種問題。由於teppic指出,您的循環清空堆棧 - 當你需要只打印一行。當你擺脫intStack,你只剩下打印,應該正常工作。

只是讓運行時系統會爲您處理的堆積;每次調用應該擔心的只是自己的部分:

上午我做了什麼? 如果沒有, 做一個簡單的事情 這個問題的一個簡化版本(也就是N-1)

在這個問題重複發生,你的「一個簡單的事情」有兩個部分:遞歸之前打印一條線;之後再打印另一行。

相關問題