break、continue使用标签跳出循环

本文通过一个具体的Java程序示例,详细介绍了循环控制语句的使用方法,包括如何使用break、continue以及标签来控制循环的执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) {
    int[][] arr = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}};
    aa:
    for (int i = 0; i < arr.length; i++) {
        bb:
        for (int i1 = 0; i1 < arr[i].length; i1++) {
            /**
             * break; 跳出内循环
             * break bb; 跳出内循环
             * brean aa; 跳出外循环
             * continue;结束本次循环
             * continue bb; 结束本次循环
             * continue aa;结束n内循环,外循环开始下一次循环
             */
            System.out.println("" + i + ":" + i1);
            continue aa;
        }
    }
}
在Java中,`break`和`continue`是控制循环执行的常用关键字,但它们只能跳出或跳过当前循环。如果需要跳出多层嵌套循环,可以使用以下几种方法: 1. **标签(Label)**: 使用标签可以跳出指定的循环标签可以与`break`和`continue`结合使用,以控制多层嵌套循环的执行流程。 ```java public class BreakWithLabelDemo { public static void main(String[] args) { int[][] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int searchValue = 5; boolean found = false; search: for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] == searchValue) { found = true; break search; } } } if (found) { System.out.println("Found at index: " + i + ", " + j); } else { System.out.println("Not found"); } } } ``` 2. **抛出异常(Exception)**: 可以在需要跳出多层循环时抛出一个异常,然后在外部捕获该异常。这种方法不推荐用于控制流程,但在某些情况下可以使用。 ```java public class ExceptionBreakDemo { public static void main(String[] args) { int[][] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int searchValue = 5; try { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] == searchValue) { throw new FoundException(); } } } } catch (FoundException e) { System.out.println("Found at index: " + i + ", " + j); } } } class FoundException extends Exception { } ``` 3. **使用标志变量(Flag Variable)**: 使用一个布尔变量来控制循环的退出。 ```java public class FlagBreakDemo { public static void main(String[] args) { int[][] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int searchValue = 5; boolean found = false; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] == searchValue) { found = true; break; } } if (found) { break; } } if (found) { System.out.println("Found at index: " + i + ", " + j); } else { System.out.println("Not found"); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值