java跳出多重循環(huán)的三種實現(xiàn)方式
java跳出多重循環(huán)的三種方式
說明:兩重for循環(huán),當 i == 2和 j == 2時,就退出多重循環(huán)體,執(zhí)行后續(xù)代碼
第一種:break 配合標簽
package cn.tedu.day04; public class Test_2020_4_9 { public static void main(String[] args) { System.out.println("三種跳出多重循環(huán)循環(huán)"); System.out.println("第一種———break 配合標簽"); loop1: // 標簽 for (int i = 1; i < 4; i++) { System.out.println(String.format("外層循環(huán)%d======", i)); for (int j = 1; j < 4; j++) { if (i == 2 && j == 2) { break loop1;// 跳轉標簽 } System.out.println(String.format("\t內(nèi)層循環(huán)%d", j)); } System.out.println(String.format("%dEND=========", i)); } System.out.println("循環(huán)結束"); } }
輸出結果:
三種跳出多重循環(huán)循環(huán)
第一種———break 配合標簽
外層循環(huán)1======
內(nèi)層循環(huán)1
內(nèi)層循環(huán)2
內(nèi)層循環(huán)3
1END=========
外層循環(huán)2======
內(nèi)層循環(huán)1
循環(huán)結束
第二種:添加判斷變量到布爾表達式中做與運算
package cn.tedu.day04; public class Test_2020_4_9 { public static void main(String[] args) { System.out.println("三種跳出多重循環(huán)循環(huán)"); System.out.println("第二種———添加判斷變量到布爾表達式中做與運算"); boolean variable = true; for (int i = 1; i < 4 && variable; i++) { System.out.println(String.format("外層循環(huán)%d======", i)); for (int j = 1; j < 4 && variable; j++) { if (i == 2 && j == 2) { variable = false; break; } System.out.println(String.format("\t內(nèi)層循環(huán)%d", j)); } System.out.println(String.format("%dEND=========", i)); } System.out.println("循環(huán)結束"); } }
輸出結果:
三種跳出多重循環(huán)循環(huán)
第二種———添加判斷變量到布爾表達式中做與運算
外層循環(huán)1======
內(nèi)層循環(huán)1
內(nèi)層循環(huán)2
內(nèi)層循環(huán)3
1END=========
外層循環(huán)2======
內(nèi)層循環(huán)1
2END=========
循環(huán)結束
第三種:try catch制造異常跳出
package cn.tedu.day04; public class Test_2020_4_9 { public static void main(String[] args) { System.out.println("三種跳出多重循環(huán)循環(huán)"); System.out.println("第三種———try catch制造異常跳出"); try { for (int i = 1; i < 4; i++) { System.out.println(String.format("外層循環(huán)%d======", i)); for (int j = 1; j < 4; j++) { if (i == 2 && j == 2) { throw new Exception(); } System.out.println(String.format("\t內(nèi)層循環(huán)%d", j)); } System.out.println(String.format("%dEND=========", i)); } } catch (Exception e) { } finally { System.out.println("循環(huán)結束"); } } }
輸出結果:
三種跳出多重循環(huán)循環(huán)
第三種———try catch制造異常跳出
外層循環(huán)1======
內(nèi)層循環(huán)1
內(nèi)層循環(huán)2
內(nèi)層循環(huán)3
1END=========
外層循環(huán)2======
內(nèi)層循環(huán)1
循環(huán)結束
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot獲取yml和properties配置文件的內(nèi)容
這篇文章主要為大家詳細介紹了SpringBoot獲取yml和properties配置文件的內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04使用apache 的FileUtils處理文件的復制等操作方式
這篇文章主要介紹了使用apache 的FileUtils處理文件的復制等操作方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07Springboot項目保存本地系統(tǒng)日志文件的實現(xiàn)方法
這篇文章主要介紹了Springboot項目保存本地系統(tǒng)日志文件的實現(xiàn)方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04