【问题标题】:Break an external while loop from an inner for loop [duplicate]从内部for循环中断外部while循环[重复]
【发布时间】:2013-06-07 09:16:10
【问题描述】:

当内部 for 循环中达到条件 stop=true 时,我想中断外部 while 循环。这可能吗?

urlsToScrape.addAll(startUrls);

    boolean stop=false;

    while(stop==false){
        for(Link url:urlsToScrape){
p.rint(url.depth+" >= "+depth);
            if(url.depth>=depth){
                p.rint("STOP!");
                stop=true;
                break;
            }
p.rint("scrape(): "+url.link+" / "+url.depth);
            processLinks(url.link,url.depth);
            urlsToScrape.remove(url);
            scrapedUrls.add(url);
        }
    }

【问题讨论】:

  • while(!stop){ 是比while(stop==false){ 更好的风格
  • 这不是已经发生了吗? while 循环的整个主体是 for 循环,因此如果在其中将 stop 设置为 true,然后跳出它,while 循环将停止迭代。
  • 抱歉,这是重复的。随意投票结束。
  • @Anthony 我认为它应该是这样工作的,但似乎没有。标签技术奏效了。
  • jlordo +1 - 你是对的。

标签: java for-loop while-loop


【解决方案1】:

使用标签:

 outofthere:
 while (stop==false){
      for(Link url:urlsToScrape){
            p.rint(url.depth+" >= "+depth);
            if(url.depth>=depth){
                p.rint("STOP!");
                stop=true;
                break outofthere;
            }
            p.rint("scrape(): "+url.link+" / "+url.depth);
            processLinks(url.link,url.depth);
            urlsToScrape.remove(url);
            scrapedUrls.add(url);
      }
  }

Oracle's documentation

【讨论】:

  • +1。我总是忘记在循环中使用标签,有时它们非常有用。
  • 谢谢,这行得通。只是等待接受它。
  • @Ankur 只是在等什么? :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2019-02-01
  • 1970-01-01
  • 2011-10-11
  • 2014-09-13
  • 2014-03-22
  • 1970-01-01
相关资源
最近更新 更多