Programming is all about coming up with the best and most efficient ways to solve the real−world problems. There are situations when you want to exit multiple loops simultaneously. This can be accomplished in Java by simply referencing the name of the loop you want to exit. In this tutorial, we'll look at how to break any outer nested loop in Java by referencing its name.
Referencing Loop Names in Java
You can break out of the Java nested loop by labelling the outer loop. This can be accomplished by using a label before the outer loop followed by a colon. The break statement and label combination can then be used inside the inner loop to exit the outer loop.
Syntax
Following is the syntax to reference the loop −
labelname :for(initialization;condition;incr/decr){
//code to be executed
}
登录后复制
Example
以下是如何在Java中使用带标签的break语句退出嵌套循环的示例:
public class Test{
public static void main(String args[]){
outerloop:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (i == 2 && j == 2) {
break outerloop;
}
System.out.println("i = " + i + ", j = " + j);
}
}
}
}
登录后复制
Output
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 0, j = 3
i = 0, j = 4
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 1, j = 4
i = 2, j = 0
i = 2, j = 1
登录后复制
In this example, the outer loop is labeled as “outerloop” using the label syntax. Within the inner loop, the if statement checks if the current values of i and j are equal to 2. If they are equal, you can use the break statement with the label “outerloop” to come out of the outer loop, otherwise, the loop continues to execute and prints the current values of i and j.
When this program is run, it will print the values of i and j for each iteration of the loop until i and j are both equal to 2 and at that point, the control will break out of the outer loop and terminate the program.
Practical Applications of Breaking Multiple Loops
各种情况都需要能够打破多个循环的能力。例如,一个程序在多维数组中搜索特定元素。如果找到了该元素,我们可以退出两个循环,从而减少处理时间。另一个例子是检查游戏中的碰撞。如果发现碰撞,我们可以退出两个循环,以防止无意义的计算。
Common Mistakes to Avoid
There are a few frequent errors to avoid when breaking multiple loops in Java. Forgetting to name the outer loop is one of the most frequent mistakes. We won't be able to use the outer loop's label in the break statement if we don't label it. Using the incorrect loop name in the break statement is another frequent error. When exiting a loop, be sure to use the right name.
Conclusion
在本文中,您学习了如何在Java中通过引用其名称来中断任何外部嵌套循环。您还了解了如何创建嵌套循环,如何跳出单个循环以及如何使用标记循环跳出多个循环,以及中断多个循环的实际应用和要避免的常见错误。
以上就是在Java中通过引用其名称打破任何外部嵌套循环的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!