自分自身を再帰的に呼び出す関数を設計しました。しかし、リターン・ステートメントは私がしたいことをしません。返品に達したことを印刷物で確認しましたが、最初の機能には戻りません。 それが入るの文:再帰関数の戻り値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文はループのために終了するからです。
これを解決するにはどうすればよいですか?私は別の方法のいずれかを考えることができません。
DLS(tmp,(depth-1));
DLSはpuzzleBoard
オブジェクトを返しますが、返された再帰的なオブジェクトは無視されますので、あなたは、オブジェクトが、このラインから返さ使用しないでください。ラインで
for(Iterator<puzzleBoard> child = generateSuccessorsIDS(pb).iterator(); child.hasNext();){
puzzleBoard tmp;
tmp=child.next();
tmp.printPuzzle();
DLS(tmp,(depth-1));
}
ルック:この繰り返しで
ます。また、Javaのコーディング規則のためのgoogleなければなりません。 –