Java:label的使用(for循环)
1 package java_test; 2 3 public class LabeledFor { 4 5 public static void main(String[]args){ 6 int i=0; 7 outer: //Cannot have statement here 8 for(;true;){ 9 inner: 10 for(;i<10;i++){ 11 System.out.println("i= "+i); 12 if(i==2){ 13 System.out.println("continue"); 14 continue; 15 } 16 if(i==3){ 17 System.out.println("break"); 18 i++; //Otherwise i never gets incremented 19 break; 20 } 21 if(i==7){ 22 System.out.println("continue outer"); 23 i++; 24 continue outer; 25 } 26 if(i==8){ 27 System.out.println("break outer"); 28 break outer; 29 } 30 for(int k=0;k<5;k++){ 31 if(k==3){ 32 System.out.println("continue inner"); 33 continue inner; 34 } 35 } 36 } 37 } 38 //Cannot break or continue to labels here 39 } 40 }
输出
1 i= 0 2 continue inner 3 i= 1 4 continue inner 5 i= 2 6 continue 7 i= 3 8 break 9 i= 4 10 continue inner 11 i= 5 12 continue inner 13 i= 6 14 continue inner 15 i= 7 16 continue outer 17 i= 8 18 break outer
用法:
1 label1: 2 outer-iteration{ 3 inner-iteration{ 4 //... 5 break;//(1) 6 //... 7 continue;//(2) 8 //... 9 continue label1;//(3) 10 //... 11 break label1;//(4) 12 } 13 }
In (1),the break breaks out of the inner iteration and you end up in the out iteration.
in(2), the continue moves back to the beginning of the inner iteration.
But in (3),the continue label1 breaks out of the inner iteration and the outer iteration,all the way back to label1. Then it does in fact continue the iteration,but starting at the outer iteration.
In(4),the break label1 also breaks all the way out to label1,but it does not reenter the iteration.It actually does break out of both iterations.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步