2012-04-09 41 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; 
}