Java中的循环结构
2022/2/2 17:12:52
本文主要是介绍Java中的循环结构,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
文章目录
- 1.while循环
- 2.break
- 3.continue
- 4.for循环
- 5.do while循环
1.while循环
基本语法格式:
while(循环条件){ 循环语句; }
循环条件为true,则执行循环语句;否则结束循环
代码示例1:打印1~10的数字
代码示例2:计算1~100的和
public class TestDemo{ public static void main(String[] args){ int n=1; int result=0; while(n<=100){ result+=n; n++; } System.out.println(result); } }
代码示例3:计算5的阶乘
public class TestDemo{ public static void main(String[] args){ int n=1; int result=1; while(n<=5){ result*=n; n++; } System.out.println(result); } }
代码示例4:计算1!+2!+3!+4!+5!
public class TestDemo{ public static void main(String[] args){ int n=1; int result=1; int sum=0; while(n<=5){ result*=n; sum+=result; n++; } System.out.println("sum="+sum); } }
2.break
break的功能是让循环提前结束
代码示例: 找到100~200中第一个3的倍数
public class TestDemo{ public static void main(String[] args){ int n=100; while(n<=200){ if(n%3==0){ System.out.println("找到了3的倍数为"+n); break; } n++; } } }
3.continue
continue的功能是跳过这次循环,立即进入下次循环
代码示例: 找到100~200 中所有3的倍数
public class TestDemo{ public static void main(String[] args){ int n=100; while(n<=200){ if(n%3==0){ System.out.println("找到了3的倍数为"+n); n++; continue; } n++; } } }
4.for循环
基本语句:
for(表达式1;表达式2;表达式3){ 循环体; }
**代码示例:**打印1-10的数字
for(int i=1;i<=10;i++){ System.out.println(i); }
for死循环:
public class TestDemo{ public static void main(String[] args){ for(byte i=0;i<=130;i++){ System.out.print(i); } } }
原因:byte的范围是-128~127,当i取127时,i+1=-128<130,故陷入死循环
注:cmd窗口终止死循环用ctrl+c ctrl+c是中断,ctrl+d是正常结束 当循环输入多个数据的时候,用ctrl+z来结束输入
5.do while循环
示例:打印1~10
int num=1; do{ System.out.println(num); num++; }while(num<=10);
注:1.do while循环最后的分号不要忘记
2.一般do while 循环很少用到,更推荐使用for和while
这篇关于Java中的循环结构的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)