2016-04-24 25 views
0

比方說,你有一個方法:如何處理Java中的遞歸關閉操作?

Object recursiveMethod() { 
    // do some things to an object. 
    Object obj = new Object(); 

    if (test fails) { 
     recursiveMethod(); // do the function again until it fails. 
    } 

    System.out.println("Returning object"); 
    return obj; 
} 

我注意到的是,如果它失敗的函數被排隊,然後從堆棧中彈出後。所以,如果失敗5次,它會打印:

Returning object //success 
Returning object //failure 
Returning object //failure 
Returning object //failure 
Returning object //failure 
Returning object //failure 

什麼是有Returning object聲明只打印一次的最佳方法?

下面是一些我已經遞歸進行的研究:http://www.toves.org/books/java/ch17-recur/

+0

使用調用遞歸方法的_wrapping_方法。然後將控制檯輸出放入包裝方法中,並將其從遞歸方法中移除。 – Seelenvirtuose

+0

這會行得通,但我認爲約翰庫格曼的解釋更優雅。 – and0rsk

+0

將「else」放在打印它的行之前。 – EJP

回答

2

您需要返回遞歸調用的結果。否則,你調用它,但扔掉它的返回值,而是返回測試失敗的對象。

if (test fails) { 
    return recursiveMethod(); 
} 

請注意,雖然這可能是一個很好的學習練習,但這不是一個好主意。遞歸是實施重試的糟糕方式,因爲每次重試堆棧的時間都會變得更長。如果您重試太多次,最終會溢出。使用循環要好得多。

while (true) { 
    //do some things to an object. 
    Object obj = new Object(); 

    if (test succeeds) { 
     System.out.println("Returning object"); 
     return obj; 
    } 
}