2012-04-09 35 views
0

我在java中有for循環的問題。我試圖做一個迭代進一步深化閩臺搜索和在深度n生成兒童的代碼看起來是這樣的:返回for循環不評估迭代器中的所有條目

for(Iterator<puzzleBoard> child = generateSuccessorsIDS(pb).iterator(); child.hasNext();){ 
    DLS(child.next(),(depth-1)); 
} 

當不使用return語句DLS確實像它應該做的,但價值不由於缺少返回語句而到達調用函數。當使用返回DLS(...)時,它只是在迭代器生成時返回第一個值。如何解決這個問題?我粘貼整個DLS並在下面調用它。

private puzzleBoard IDS(String initial){ 
    puzzleBoard pb = new puzzleBoard(initial,0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>()); 

    puzzleBoard result=new puzzleBoard("999999999",0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>()); 
    for(int depth=0;depth<3;depth++){//Repeat 
     System.out.println("DP "+depth); 
     result = DLS(pb,depth); 
     System.out.println("Here: "+result.toString()); 
     if(result.isGoalState()) 
      return result; 
    } 
    return new puzzleBoard("999999999",0,new Vector<Integer>()); 
} 

private puzzleBoard DLS(puzzleBoard pb, int depth){ 

    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();){ 
      DLS(child.next(),(depth-1)); 
     } 
    } 
    else 
     return new puzzleBoard("999999999",0,new Vector<Integer>(),new Vector<puzzleBoard>(),new Vector<puzzleBoard>()); 
    return pb; 
} 
+0

您將不得不向我們展示一些支持您的初始斷言的代碼。 – 2012-04-09 05:22:47

回答

1

可能是我錯了,但我覺得你應該把你的循環之外,你在哪裏實際調用你的函數DLS(puzzleBoard pb, int depth)首次.....裏面你else if只能撥打DLS(pb,depth);

1

您正在遍歷迭代器中的每個元素併爲每個元素調用DLS,但是您會返回從循環內調用第一個元素的結果,繞過所有其他元素。您需要決定如何將循環中所有呼叫的返回值組合到DLS

如果您只想在爲每個元素調用DLS後返回null,請在循環後添加return語句。

else if (depth>0) { 
    for (...) { 
     DLS(...); 
    } 
    return null; 
}