Java基础00-循环语句7
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; } } }