\(^_^)/ Java 跳出多层嵌套循环

方法一: 标号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));
			}
		}
	}
}

  

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值