简体   繁体   English

使用递归并中断for循环

[英]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. 当其执行“外部中断”时,它将中断外部for循环。 Which is good. 哪个好 But the outer for loop continues to start once again after breaking out. 但是外部的for循环在中断后仍会再次开始。 Why is that so? 为什么会这样?

My isFound is an instance variable and is set to false. 我的isFound是一个实例变量,并设置为false。

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. 回答您的原始问题:代码继续,因为标记的break不会“将控制流”转移到标签,而是转移到标记语句之后的语句。 Let me illustrate with a tree (my ASCII art isn't great, but bear with me..) 让我用一棵树来说明(我的ASCII艺术不是很好,但是请忍受..)

- 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. 现在,如果您中断了Sub1Subitem2的操作,则可以退出该子节点集合(Sub1Subitem#),使您跳出SINGLE级别,这意味着您将绕过Sub1Subitem3而最终到达SubItem2。您突破了一个级别,但仍在运行,因为您递归了多个级别。

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. 如果您试图完全脱离周期(这意味着,如果您在Sub1Subitem2中找到了答案,按照示例,您已经完成了,不需要做更多的事情),则需要突破所有级别,而不仅仅是一个级别。 This other StackOverflow answer has a suggestion for doing just that. 这个其他StackOverflow答案对此有一个建议。

1) The simple solution: 1)简单的解决方案:

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

2) Another, better solution would be not to use "break". 2)另一个更好的解决方案是不使用“ break”。 Just modify the method from "void" to "boolean", return the boolean result, and don't use global variable "isFound". 只需将方法从“ void”修改为“ boolean”,返回布尔结果,而不使用全局变量“ isFound”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM