She*_*ard 39 java syntax loops for-loop break
如果我在循环中循环并且一旦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.
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jig*_*shi 61
使用带标签的休息:
mainloop:
for(){
for(){
if (some condition){
break mainloop;
}
}
}
Run Code Online (Sandbox Code Playgroud)
另见
Roh*_*ain 28
您可以为循环添加标签,并使用它labelled break
来打破适当的循环: -
outer: for (...) {
inner: for(...) {
if (someCondition) {
break outer;
}
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅以下链接
dan*_*dan 12
你可以return
从该功能中获得控制权.或者使用丑陋的break labels
方法:)
如果for
语句后面还有其他代码部分,则可以在函数中重构循环.
IMO,在OOP中应该不鼓励使用中断和继续,因为它们会影响可读性和维护.当然,有些情况下它们很方便,但总的来说我认为我们应该避免使用它们,因为它们会鼓励使用goto风格的编程.
显然,这个问题的变化很多.彼得在这里使用标签提供了一些好的和奇怪的用途
归档时间: |
|
查看次数: |
30318 次 |
最近记录: |