如何在双/嵌套循环中脱离主/外循环? [英] How do I break from the main/outer loop in a double/nested loop?

查看:42
本文介绍了如何在双/嵌套循环中脱离主/外循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在循环中有循环,并且一旦满足 if 语句,我想中断主循环,我该怎么做?

If I have loop in a loop and once an if statement is satisfied I want to break main loop, how am I supposed to do that?

这是我的代码:

for (int d = 0; d < amountOfNeighbors; d++) {
    for (int c = 0; c < myArray.size(); c++) {
        if (graph.isEdge(listOfNeighbors.get(d), c)) {
            if (keyFromValue(c).equals(goalWord)) { // Once this is true I want to break main loop.
                System.out.println("We got to GOAL! It is "+ keyFromValue(c));
                break; // This breaks the second loop, not the main one.
            }
        }
    }
}

推荐答案

使用带标签的中断:

mainloop:
for(){
 for(){
   if (some condition){
     break mainloop;
   }
  }
}

<小时>

另见

这篇关于如何在双/嵌套循环中脱离主/外循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆