更新時(shí)間:2023年05月15日09時(shí)29分 來源:傳智教育 瀏覽次數(shù):
在Java中,我們可以使用break語句來跳出當(dāng)前循環(huán)。如果我們需要跳出多重嵌套循環(huán),可以使用帶標(biāo)簽的break語句。
下面是一個(gè)使用帶標(biāo)簽的break語句跳出多重嵌套循環(huán)的示例代碼:
outerloop: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (i == 5 && j == 5) { break outerloop; } System.out.println("i = " + i + ", j = " + j); } }
在這個(gè)示例代碼中,我們使用outerloop標(biāo)簽來標(biāo)識外部循環(huán)。當(dāng)i和j的值都等于5時(shí),我們使用break語句和標(biāo)簽outerloop跳出外部循環(huán)。
當(dāng)運(yùn)行這個(gè)示例代碼時(shí),它將輸出:
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 0, j = 3 i = 0, j = 4 i = 0, j = 5 i = 0, j = 6 i = 0, j = 7 i = 0, j = 8 i = 0, j = 9 i = 1, j = 0 i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 1, j = 4 i = 1, j = 5 i = 1, j = 6 i = 1, j = 7 i = 1, j = 8 i = 1, j = 9 i = 2, j = 0 i = 2, j = 1 i = 2, j = 2 i = 2, j = 3 i = 2, j = 4 i = 2, j = 5 i = 2, j = 6 i = 2, j = 7 i = 2, j = 8 i = 2, j = 9 i = 3, j = 0 i = 3, j = 1 i = 3, j = 2 i = 3, j = 3 i = 3, j = 4 i = 3, j = 5 i = 3, j = 6 i = 3, j = 7 i = 3, j = 8 i = 3, j = 9 i = 4, j = 0 i = 4, j = 1 i = 4, j = 2 i = 4, j = 3 i = 4, j = 4 i = 4, j = 5 i = 4, j = 6 i = 4, j = 7 i = 4, j = 8 i = 4, j = 9
可以看到,當(dāng)i和j的值都等于5時(shí),外部循環(huán)被中斷,并且程序直接跳出循環(huán),沒有輸出剩余的i和j的值。
需要注意的是,帶標(biāo)簽的break語句只能用于循環(huán)語句中,不能用于其他類型的語句中。此外,continue語句也可以使用帶標(biāo)簽的形式,用于在多重嵌套循環(huán)中跳過當(dāng)前迭代并繼續(xù)下一次迭代。
北京校區(qū)