Java基础00-循环语句7
2024-09-07 15:32:57
1. for循环语句
1.1 循环结构
1.2 for循环语句的格式
执行流程图:
1.3 案例
(1)输出数据
(2)求和
(3)求偶数和
(4)水仙花
public static void main(String[] args) {
int count = 0;
for (int i = 100; i < 1000; i++) {
int ge = i % 10;
int shi = i / 10 % 10;
int bai = i / 10 / 10 % 10;
int result = ge * ge * ge + shi * shi * shi + bai * bai * bai;
if (result == i) {
System.out.println(result+"是水仙花数");
}
}
}
(5)统计水仙花数
public static void main(String[] args) {
int count = 0;
for (int i = 100; i < 1000; i++) {
int ge = i % 10;
int shi = i / 10 % 10;
int bai = i / 10 / 10 % 10;
int result = ge * ge * ge + shi * shi * shi + bai * bai * bai;
if (result == i) {
count++;
}
}
System.out.println("水仙花共有:" + count + "个");
}
2. while循环语句
2.1 while循环语句格式
执行流程图:
2.2 案例
public static void main(String[] args) {
int count = 0;
int zf = 8844430;
double paper = 0.1;
while(paper <= zf) {
count++;
paper *= 2;
}
System.out.println(count);
}
3. do…while循环语句
3.1 do…while循环语句格式
执行流程图:
3.2 三种循环的区别
死循环会有一直输出,除非手动停止。
4. 跳转控制语句
4.1 添转控制语句概述
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0){
continue;
}
System.out.println(i);//输出:1 3 5
} for (int j = 1; j <= 5; j++) {
if(j % 2 == 0){
break;
}
System.out.println(j);//输出:1
}
}
5. 循环嵌套
5.1 循环嵌套概述
代码实例:
改进:
继续改进:
结果都为:
6. Randdom
6.1 Randdom的作用和步骤
6.2 案例
public static void main(String[] args) {
Random r = new Random();
int number = r.nextInt(100)+1;
System.out.println("随机数是"+number);
while (true){
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要猜的数字(1-100):");
int guessNumber = sc.nextInt();
if(guessNumber > number){
System.out.println("你猜的数字"+guessNumber+大了");
}else if(guessNumber < number){
System.out.println("你猜的数字"+guessNumber+"小了");
}else{
System.out.println("猜中了");
break;
}
}
}
最新文章
- Python: 利用Python进行数据分析 学习记录
- Javascript闭包(狗血剧情,通俗易懂)
- 2015.10.18 do while练习
- Java提高篇(三三)-----Map总结
- django 快速实现注册
- Windows OpenVPN Client and tls-auth
- Cygwin解决Windows远程登录linux服务器
- Day13 SQLAlchemy连表操作和堡垒机
- wxWidgets刚開始学习的人导引(3)——wxWidgets应用程序初体验
- 网络数据(socket)传输总结
- 一个web开发框架
- Openstack中keystone与外部LDAP Server的集成
- [SCOI2003]字符串折叠
- 常用的redis服务命令。
- Zookeeper环境搭建
- Android添加百分比布局库时显示Failed to resolve: com.android.support.percent:问题
- codeforces622B
- HAProxy基础原理介绍
- GIS案例学习笔记-ArcGIS整图大图出图实例教程
- cdh 5.13 centos6.9安装