Java笔记——流程控制LOOP循环 笔记二
本篇笔记2延续流程控制LOOP循环的讲解,如需要全部笔记,请 移步笔记1
loop 笔记一
ForTest3
public class ForTest3 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 1){
//筛选奇数1 3 5 7 9
sum += i;
}
}
System.out.println("1-10中的奇数和为"+sum);
System.out.println("-------------------");
int sum2 = 0;
for (int i = 1; i <= 10; i+=2) {
sum2+=i;
}
System.out.println("1-10中的奇数和为"+sum);
}
}
ForTest4
需求
1·水仙花是一个三位数
2·水仙花的个位,十位,百位的数字立方和等于原数
分析:
定义一个for循环,找100到999
每次访问到数据后,提取该数据的个位,十位,百位数字
使用if判断:个位,十位,百位的数字立方和是否邓宇原数,等于则输出该数
个数:
count
package com.mumei.loop;
public class ForTest4 {
public static void main(String[] args) {
int count = 0;
for (int i = 100; i <= 999; i++) {
int ge = i % 10;
int shi = i /10 % 10;
int bai = i / 100;
//检索条件
if (ge*ge*ge+shi*shi*shi+bai*bai*bai == i) {
System.out.print(i+"\t");
count++;
}
}
System.out.println();//换行
System.out.println("水仙花的个数是"+count);
}
}
while
功能
while格式:
while (循环条件){
循环体语句;
迭代语句;
}
while (i ❤️){
System.out.println(“I donnt wanna wake up from this sweet sweet dream.–Enkidu”);
i++;
}
什么时候用for,什么时候用while
功能上完全一样,for能解决的while也能解决,反之亦然
使用范围:知道循环几次用for循环,不知道循环几次建议使用while
package com.mumei.loop;
public class WhileDemo5 {
public static void main(String[] args) {
//目标:学会使用while循环,并理解
int i = 0;
while (i <3){
System.out.println("I donnt wanna wake up from this sweet sweet dream.--Enkidu");
i++;
}
System.out.println("-----------------------");
int j = 0;
while (j < 3){
System.out.println("I donnt wanna wake up from this sweet sweet dream.--Enkidu");
j++;
}
}
}
WhileTest6
需求:珠穆朗玛峰的高度是8848860mm,使纸张对折,问折叠多少次之后使纸的厚度达到珠穆朗玛峰的高度
纸张厚度0.1mm
package com.mumei.loop;
public class WhileTest6 {
public static void main(String[] args) {
//定义自变量
double peakHeight = 8848860;
double paperThickness = 0.1;
//定义while循环
int count = 0;//计数器
while (paperThickness < peakHeight){
paperThickness *=2;//纸张厚度增加
count++;
}
System.out.println("折叠"+count+"次");
System.out.println("纸张的最终厚度是"+paperThickness+"mm");
}
}