如何突破Java中的嵌套循環(huán)?我有一個嵌套的循環(huán)結構,如下所示:for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break; // Breaks out of the inner loop
}
}}現(xiàn)在我怎樣才能打破這兩個循環(huán)呢?我看過類似的問題,但沒有一個具體涉及Java。我無法應用這些解決方案,因為大多數(shù)人使用Gotos。我不想把內(nèi)環(huán)放在另一種方法上。我不想重新運行循環(huán)。當中斷時,我完成了循環(huán)塊的執(zhí)行。
3 回答

慕妹3146593
TA貢獻1820條經(jīng)驗 獲得超9個贊
break
public class Test { public static void main(String[] args) { outerloop: for (int i=0; i < 5; i++) { for (int j=0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking"); break outerloop; } System.out.println(i + " " + j); } } System.out.println("Done"); }}
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done

拉風的咖菲貓
TA貢獻1995條經(jīng)驗 獲得超2個贊
private static String search(...) { for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... return search; } } } return null; }
public class Test { public static void main(String[] args) { loop(); System.out.println("Done"); } public static void loop() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking"); return; } System.out.println(i + " " + j); } } }}

弒天下
TA貢獻1818條經(jīng)驗 獲得超8個贊
search: { for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break search; } } }}
添加回答
舉報
0/150
提交
取消