user1669488
user1669488

Reputation: 227

Using recursion and breaking a for loop

I have this code

public void getItems(Node node) {
  if (!isFound) {
    NodeList list = node.getChildNodes();
    outer:
    for (int i = 0; i < list.getLength(); i++) {
      Node childNode = list.item(i);
      if (node.getNodeName().equals("test")) {
        for (int size=0; size<node.getChildNodes().getLength(); size++) {
          //Some code here
        }
        isFound = true;
        break outer;
      }
      getItems(childNode);
    }
  }
}

When its executed the "break outer" it breaks out of the outer for loop. Which is good. But the outer for loop continues to start once again after breaking out. Why is that so?

My isFound is an instance variable and is set to false.

Upvotes: 0

Views: 144

Answers (2)

mentallurg
mentallurg

Reputation: 5207

1) The simple solution:

for (int i = 0; i < list.getLength() && !isFound; i++) {

2) Another, better solution would be not to use "break". Just modify the method from "void" to "boolean", return the boolean result, and don't use global variable "isFound".

Upvotes: 1

Omnidisciplinarianist
Omnidisciplinarianist

Reputation: 247

To answer your original question: the code continues because the labeled break doesn't "transfer control flow" to the label, but to the statement just following the labeled statement. Let me illustrate with a tree (my ASCII art isn't great, but bear with me..)

- Item1
+- Subitem1
 +- Sub1Subitem1
 +- Sub1Subitem2 >==|
 +- Sub1Subitem3    | break outer;
+- Subitem2 <=======|
 +- Sub2Subitem1
...
- Item N

Now, if you do your break on, say, Sub1Subitem2, you break out of walking that collection of child nodes (Sub1Subitem#), popping you back out a SINGLE level, which should mean you'll end up at SubItem2, bypassing Sub1Subitem3 because you broke out the one level, but still running because you've recursed MORE than one level.

If you are trying to break completely out of the cycle (meaning if you find the answer in Sub1Subitem2, as per the example, you are done and need do no more) you'll need to break out of ALL levels, not just one. This other StackOverflow answer has a suggestion for doing just that.

Upvotes: 2

Related Questions