如何指定跳出多层循环

方法一: 标号label:在外面的循环语句前定义一个标号,然后再里层循环体代码中使用带有标号的break语句,标号用于跳出多层嵌套循环,你可以用标号label标出你想退出哪一个语句。规定标号label必需放在循环之前(意味着循环必需紧跟着标号)。类似的功能我们在C#中只能用goto进行,Java虽然保留了goto关键词,却不允许使用 (goto为保留字)。需要注意的是Label和下面的循环语句间不能有其他代码。标号同时适用于break和continue。从设计角度来说是用Label、goto都不是好主意。

public class OutLoopWithLabel{  
    public static void main(String args[]) {  
        ok: // 设定跳出当前循环的一个标号 注意ok后面是冒号:  
        for (int i = 0; i < 10; i++) {  
            for (int j = 0; j <= 10; j++) {  
                System.out.println("i=" + i + ",j=" + j);  
                if (j == 5)  
                    break ok; // 设定跳出当前循环的一个标号  
            }  
        }  
    }  
}  

方法二:boolean,break组合:通过Boolean型条件变量和break的组合,由内层循环在跳出(break)前改变条件变量,外层循环检测条件变量改变时终止外层循环。

public class OutLoopWithBooleanBreak {  
    public static void main(String args[]) {  
        int arr[][] = { { 1, 2, 3 }, { 4, 5, 6, 7 }, { 9 } };  
        boolean found = false;  
        System.out.println("arr.length " + arr.length);  
        for (int i = 0; i < arr.length && !found; i++) {  
            for (int j = 0; j < arr[i].length; j++) {  
                System.out.println("i=" + i + ",j=" + j);  
                if (arr[i][j] == 5) {  
                    found = true; // 修改了第一个循环中的参数found  
                    break; // 跳出循环  
                }  
            }  
        }  
    }  
}  

方法三:return:在内层循环直接跳出整个方法。

public class OutLoopWithReturn {  
    public static void main(String[] args) {  
        for (int i = 0; i < 10; i++) {  
            for (int j = 0; j < 10; j++) {  
                if (i * j > 60) {  
                    return;  
                }  
                System.out.println(i + " * " + j + " = " + (i * j));  
            }  
        }  
    }  
}  

方法四:throw Exception:在内层循环直接抛出异常。

public class OutLoopWithException {  
    public static void main(String[] args) throws Exception {  
        for (int i = 0; i < 10; i++) {  
            for (int j = 0; j < 10; j++) {  
                if (i * j > 60) {  
                    throw new Exception("exception");  
                }  
                System.out.println(i + " * " + j + " = " + (i * j));  
            }  
        }  
    }  
}  

总结:
1.我们可以通过在某个需要跳出的循环前面添加标号的形式 outer:,我们在需要跳出的地方判断欧break outer;跳出指定位置循环。
2.我们可以定义一个boolean类型的变量 boolean found = false; 在需要跳出的循环中加入一个条件判断 &&!found,然后我们在内层循环中如果想要跳出该循环,只需要把found值改为true,然后break;就行了。
3.可以在内层循环中自接return;即可跳出整个循环。
4.可以在需要跳出循环的地方抛出一个异常 throw new Exception(“exception”); 简单粗暴。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值