int x=10; do { System.out.println("value of x:"+x); x++; } while(x<20); //do while循环
1 int x=10; 2 while(x<20) { 3 System.out.println("value of x:"+x); 4 x++; 5 } //while循环
while(布尔表达式) 只要布尔表达式内容为真 循环体就会一直循环下去
do while 即使不满足条件 也至少执行一次
1 for(int x=10;x<20;x=x+1) 2 { 3 System.out.println("value of x:" +x); 4 } //for循环 for语句 和while 语句后面没有;
循环次数在循环执行前就已经确定了
注意for循环内部用 ;
1 int [] numbers= {10,20,30,40,50,60}; 2 for (int x:numbers) { 3 System.out.print(x); 4 System.out.print(','); 5 } 6 System.out.print("\n"); 7 String []names = {"Jame","Tom","Jerry"}; 8 for(String name : names) { 9 System.out.print(name); 10 System.out.print(','); 11 } //数组增强for循环
Java增强for循环
for(声明语句:表达式)
声明语句:声明新的局部变量,变量类型必须与数组元素匹配
表达式:要访问的数组名,或者是返回值为数组的方法
1 int [] numbers= {10,20,30,40,50}; 2 for(int x:numbers) { 3 if(x==30) { 4 break; 5 } 6 System.out.println(x); 7 } //break关键字
break通常应用于switch语句中,用于跳出循环
break跳出最里层的循环 并且执行该循环下面的语句
1 int [] numbers= {10,20,30,40,50}; 2 for(int x:numbers) { 3 if(x==30) { 4 continue; 5 } 6 System.out.println(x); 7 } //continue关键字
continue适用于许多的循环结构
for循环中,continue语句使程序立即跳转到更新语句
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步