2013-05-04 2 views
0

У меня есть возврат, однако вы можете увидеть строку "this will not print", которая не должна быть достигнута после того, как произойдет вызванное событие return.Мой возврат не прекращает выполнение

Что происходит?

Code

Вот вся процедура, это черновик в данный момент ...:

private void greedySearch (String lookForNode) 
{ 
    // Note: Available vars 
    // reqStartNode 
    // reqEndNode 

    // Search through entire tree looking for... 
    System.out.println("Searching through entire tree looking for "+lookForNode); 
    for (int i = 0; i < treeList.size(); i++) { 

     Data currentNode = treeList.get(i); 

     // ... reqStartNode 
     if (currentNode.getNodeName().equals(lookForNode)) 
     { 
      System.out.println("Found matching node. currentNode.getNodeName=" + currentNode.getNodeName()+" lookForNode="+lookForNode); 

      // Check to see if there's any children? 
      if (currentNode.childrenList.size() > 0) 
      { 
       // Find smallest child by node 
       double smallestHeuristic = currentNode.childrenList.get(0).getHeuristic(); 
       String smallestNode = currentNode.childrenList.get(0).getNodeName(); 
       for (int ii = 1; ii < currentNode.childrenList.size(); ii++) 
       { 
        if (currentNode.childrenList.get(ii).getHeuristic() < smallestHeuristic) 
        { 
         smallestHeuristic = currentNode.childrenList.get(ii).getHeuristic(); 
         smallestNode = currentNode.childrenList.get(ii).getNodeName(); 
        } 
       } 

       // Check to see if smallest child by node is reqEndNode 
       if (smallestNode == reqEndNode) 
       { 
        System.out.println("FOUND GOAL "+smallestNode); 

        // Quit because we found the answer 
        return; 
       } 
       // Expand that node 
       else 
       { 
        greedySearch (smallestNode); 
       } 
      } 
      // No children, we've reached the end 
      else 
      { 
       System.out.println("We've reached the end at "+currentNode.getNodeName()); 

       // Quit because we've reached no further children to expand 
       return; 
      } 
      System.out.println("This will not print");  
     } 
     else 
     { 
      System.out.println("Skipped node "+currentNode.getNodeName()); 
     } 
    } 

    System.out.println("FINISHED SEARCH"); 

} 

Edit:

Правильное решение, я понял, делал return после Я называю рекурсивную процедуру следующим образом:

greedySearch (smallestNode); 
// Quit because we are now going recursive, our job here is done 
return; 

Мой Ouput Сейчас:

Searching through entire tree looking for S 
Skipped node A 
Skipped node B 
Skipped node C 
Skipped node D 
Skipped node E 
Skipped node F 
Skipped node G 
Skipped node G 
Found matching node. currentNode.getNodeName=S lookForNode=S 
Searching through entire tree looking for A 
Found matching node. currentNode.getNodeName=A lookForNode=A 
Searching through entire tree looking for B 
Skipped node A 
Found matching node. currentNode.getNodeName=B lookForNode=B 
Searching through entire tree looking for C 
Skipped node A 
Skipped node B 
Found matching node. currentNode.getNodeName=C lookForNode=C 
We've reached the end at C 
+2

Я думаю, что ваш код не вводит еще блок. –

+0

Является ли это рекурсивным методом? – jlordo

+0

Покажите нам весь код. –

ответ

4

Ничего странного не происходит. Я вижу хотя бы один путь кода, для которого это может произойти.

В вложенного вызова, это выполняется:

 else 
     { 
      System.out.println("We've reached the end at "+currentNode.getNodeName()); 

      // Quit because we've reached no further children to expand 
      return; 
     } 

Затем возвращается к внешнему вызову:

  else 
      { 
       greedySearch (smallestNode); // Resuming from here... 
      } 
     } 
     else 
     { 
      // ...all this is skipped (because we are in the else block 
      // of an if that was true)... 
     } 
     // ...and this is printed. 
     System.out.println("This will not print");  
    } 

Другими словами, в то время как эти две линии вы смотрите на являются , действительно, взаимоисключающие во время одного вызова вашего рекурсивного метода, они не являются взаимоисключающими между двумя вложенными вызовами. И сообщения, которые они печатают, могут отображаться в последовательности, как в случае с вашим выходом.

+0

Я забыл, что это было рекурсивным. :) Спасибо, у меня был долгий день. – gbhall

+0

Не задумываясь, есть ли способ закончить его для всех рекурсивных вызовов на пути вверх? – gbhall

+1

Поскольку этот метод является 'void', возможно, вы можете превратить его в' bool' и вернуться к его вызывающему, должен ли он продолжать или останавливаться полностью. –

Смежные вопросы