我設計了一個遞歸調用自身的函數。但是回報聲明並沒有做我想做的事情。我們檢查了打印件是否已達到退貨,但未返回到初始功能。 聲明它進入:在遞歸函數中的返回值JAVA
if(depth==0 && pb.isGoalState()){
System.out.println("!!!!!WOOOOOW!!!!!");
return pb;
}
中的println顯示了罰款,但返回PB,當事情變得怪異。
當談到回功能:
result = DLS(pb,depth); //never returns here!!!
System.out.println("Here: "+result.toString());
它永遠不會打印出印刷正上方。我看不出有什麼問題!我檢查了我自己設計的其他方法。
private puzzleBoard IDS(String initial){
puzzleBoard pb = new puzzleBoard(initial,0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>());
int depth=0;
puzzleBoard result=new puzzleBoard("999999999",0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>());
while(true){//Repeat
System.out.println("DP "+depth);
result = DLS(pb,depth);
System.out.println("Here: "+result.toString());
if(result.isGoalState())
return result;
depth++;
}
}
private puzzleBoard DLS(puzzleBoard pb, int depth){
System.out.println("AVskilj depth "+depth+" "+(depth==0 && pb.isGoalState()));
pb.printPuzzle();
if(depth==0 && pb.isGoalState()){
System.out.println("!!!!!WOOOOOW!!!!!");
return pb;
}
else if(depth>0){
for(Iterator<puzzleBoard> child = generateSuccessorsIDS(pb).iterator(); child.hasNext();){
puzzleBoard tmp;
tmp=child.next();
tmp.printPuzzle();
DLS(tmp,(depth-1));
}
}
else
return new puzzleBoard("999999999",0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>());
return pb;
}
所以我的問題是,現在仍然在代碼
for(Iterator<puzzleBoard> child = generateSuccessorsIDS(pb).iterator(); child.hasNext();){
DLS(child.next(),(depth-1));
}
當我不使用DLS之前返回的這部分(child.next(),(深度1 ));它按預期經過每個孩子,但由於缺少回報而沒有存儲價值。當我在它之前使用return時,它只是通過迭代器中的第一個子元素,而忽略其餘元素,因爲return語句會終止循環。
如何解決這個問題?我想不出另一種方式。
你也應該谷歌的Java編碼慣例。 – 2012-04-08 14:23:56