Java入门之循环结构
(1)while循环
1 public static void main(String[] args) { 2 //输出1-50 3 int i = 0; 4 5 while(i < 50){ 6 i++; 7 System.out.println(i); 8 } 9 10 }
(2)do...while循环
1 public static void main(String[] args) { 2 //输出1-50 3 int i = 0; 4 5 do{ 6 i++; 7 System.out.println(i); 8 }while(i < 50); 9 10 11 }
(3)for循环
1 { 2 3 public static void main(String[] args) { 4 //输出1-50 5 6 for(int i = 1; i <= 50; i++){ 7 System.out.println(i); 8 } 9 10 }
for循环还有另外2种写法:
1 int i; 2 for(i = 1; i <= 50; i++){ 3 4 }
1 int i = 1; 2 for(; i <= 50; i++){ 3 4 }
for循环更加灵活,高效,避免使用while出现死循环,导致程序奔溃。若条件不满足,while语句不会执行,do...while语句则会执行一次。
1 public static void main(String[] args) { 2 3 int a = 0; 4 while(a<0){ 5 System.out.println("while"); 6 } 7 System.out.println("====================="); 8 do{ 9 System.out.println("do...while"); 10 }while(a<0); 11 12 }
(4)增强型for循环
1 public static void main(String[] args) { 2 int[] num = {10,20,30,40}; 3 for(int n : num){ 4 System.out.println(n); 5 } 6 7 }
增强型for循环一般用于数组以及集合的遍历。
=================================================
break和continue
(1)break用于强行中断当前循环,不会终止程序。
1 public static void main(String[] args) { 2 while (true){ 3 while (true){ 4 while (true){ 5 break; 6 } 7 System.out.println("second"); 8 break; 9 } 10 System.out.println("first"); 11 break; 12 } 13 }
(2)continue用于跳出某次循环,继续下一次循环。
1 public static void main(String[] args) { 2 3 for(int i = 1; i <= 10; i++){ 4 //不能被3整除,则跳出循环不执行打印语句,继续下一次循环 5 if(i % 3 != 0){ 6 continue; 7 } 8 System.out.println(i); 9 } 10 }
带标签的continue直接跳到标签处,继续执行代码。不建议使用。
1 public static void main(String[] args) { 2 //查找1-100的质数 3 out:for (int i = 1; i < 100; i++) { 4 for(int j = 2; j <= i / 2; j++){ 5 if(i % j == 0){ 6 continue out; 7 } 8 } 9 System.out.print(i + " "); 10 } 11 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!