1.2.8、循环结构语句
1.2.8.1、for
package myOperator;
/**
* Created by JackFeng on 2020/2/26.
*/
/*
* for循环语句的格式:
* for(初始化语句;判断条件语句;控制条件语句){
* 循环体语句:
*
* }
*
* */
public class ForDemo {
public static void main(String[] args) {
// 输出10次 hello
for (int i=1;i<=10;i++){
System.out.println("hello"+i);
}
// 获取 1-5
for (int x =1 ;x <=5;x++){
System.out.println("-----");
System.out.println(x);
}
// 获取 5-1
for (int x = 5; x >= 1; x--) {
System.out.println("======");
System.out.println(x);
}
// 1-5 求和
//初始化值为0
int sum = 0;
for (int x =1;x<=5;x++){
sum = sum + x;
// sum += x;
System.out.println("累加值为:"+sum);
}
System.out.println("sum"+sum);
}
}
1-100 偶数和
// 结果:2550
int s = 0;
for (int x =1;x<=100;x++){
if (x%2 ==0){
s += x;
}
}
System.out.println("1-100偶数求和为:"+s);
水仙花
//经典案例 水仙花数
// EG: 153
// 个位:153%10
// 十位:153/10%10
// 百位:153/10/10%10
int count = 0;
for (int x=100;x<=999;x++){
int gw =x % 10;
int sw =x/10 % 10;
int bw =x/10/10 % 10;
if ((gw*gw*gw +sw*sw*sw + bw*bw*bw )==x){
System.out.println(x);
count++; //统计次数
}
}
//输出统计值
System.out.println(count);
1.2.8.2、while
package myOperator;
/**
* Created by JackFeng on 2020/2/26.
*/
public class WhileDemo {
public static void main(String[] args) {
// 输出10次 你好
// for 实现
for (int i =1;i<=10;i++){
System.out.println("你好");
}
// while 实现
int s = 1;
while (s<=10){
System.out.println("Nihao");
s++;
}
}
}
1.2.8.3、do…while
package myOperator;
/**
* Created by JackFeng on 2020/2/26.
*/
public class DoWhileDemo {
public static void main(String[] args) {
// 输出10次 HI
for (int i =1;i<=10;i++){
System.out.println("Hi");
}
// do while 改写
int x = 1;
do {
// 循环体语句
System.out.println("HI hi");
// 控制条件语句
x++;
}
// 判断体语句
while (x <= 10);
}
}
1.2.8.4、 三种循环语句区别
A: do…while 循环至少执行一次循环体
B: for和 while 必须判断条件成立才执行循环体
package myOperator;
/**
* Created by JackFeng on 2020/2/26.
*/
public class XunDemo {
public static void main(String[] args) {
int x = 3;
while(x <3){
System.out.println("while 循环体");
x++;
}
int y = 3;
do {
System.out.println(" do while 循环ti ");
y++;
} while (y < 3);
}
}
for 和 while 区别
for循环结束后,初始化变量不可被使用。
while 循环结束后,初始化变量可以被使用。
推荐使用顺序:
for
while
do…while
// for 和 while 的区别
public static void main(String[] args) {
//for
for (int i = 0; i <5 ; i++) {
System.out.println("这里是for循环");
}
// System.out.println("i:"+i); 这里是调用不了的
//while
int x =0;
while (x<5){
System.out.println("while循环");
x++;
}
System.out.println("x:"+x);
}
期待您的进步