【笔记】关于退出嵌套for循环的正确姿势

mac2025-03-24  11

有这么一段代码

String[] abc = {"a", "b", "c"}; String[] num = {"1", "2", "3"}; for(int i = 0 ; i < abc.length ; i++) { for(int j = 0 ; j < num.length ; j++) { System.out.println(abc[i] + num[j]); } }

运行结果

a1 a2 a3 b1 b2 b3 c1 c2 c3

如果num[]遍历只循环到字符 "2",即只输出"1","2"不输出"3"

String[] abc = {"a", "b", "c"}; String[] num = {"1", "2", "3"}; for(int i = 0 ; i < abc.length ; i++) { for(int j = 0 ; j < num.length ; j++) { System.out.println(abc[i]+num[j]); if(j == 1) { break; } } }

执行结果

a1 a2 b1 b2 c1 c2

break只会退出当前的for循环,跳到外层的for循环继续执行

那么如果num[]遍历到"2",要退出整个嵌套for循环怎么办呢?

可以在最层的for循环前加一个标签(标签名自己明命即可)

String[] abc = {"a", "b", "c"}; String[] num = {"1", "2", "3"}; needle : for(int i = 0 ; i < abc.length ; i++) { for(int j = 0 ; j < num.length ; j++) { System.out.println(abc[i]+num[j]); if(j == 1) { break needle; } } }

执行结果

a1 a2

当然,只退出里层的for循环也可以这么写

String[] abc = {"a", "b", "c"}; String[] num = {"1", "2", "3"}; needle : for(int i = 0 ; i < abc.length ; i++) { for(int j = 0 ; j < num.length ; j++) { System.out.println(abc[i]+num[j]); if(j == 1) { continue needle; } } ... System.out.println("china"); ... }

这样写,既会退出里层for循环,而且里层for循环后面的语句都不会被执行。

我在写的时候就把break记反了,我记成break是直接退出所有嵌套循环,因为这个跟同事打赌,结果输了一瓶维他奶 (╯‵□′)╯︵┻━┻

最新回复(0)