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/
使用調用遞歸方法的_wrapping_方法。然後將控制檯輸出放入包裝方法中,並將其從遞歸方法中移除。 – Seelenvirtuose
這會行得通,但我認爲約翰庫格曼的解釋更優雅。 – and0rsk
將「else」放在打印它的行之前。 – EJP