如何在双/嵌套循环中脱离主循环/外循环?

2022-09-01 03:30:08

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

这是我的代码:

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.
            }
        }
    }
}

答案 1

使用带标签的中断:

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

另请参见


答案 2

您可以向循环添加标签,并使用它来打破相应的循环:-labelled break

outer: for (...) {
    inner: for(...) {
        if (someCondition) {
            break outer;
        }
    }
}

有关详细信息,请参阅以下链接: