2. 循环结构
2.1 为什么要用循环
生活中很多重复的事情,周而复始
吃饭,睡觉,撸猫,学习,上课…
代码中一定存在需要循环出现的情况,如果不使用循环,会导致以下一些问题
1. 阅读性极差!!!
2. 维护性极差!!!
3. 代码冗余!!!
2.2 while循环
while (/* 循环条件 true or false */) {
// 循环体
// (循环条件变更)
}
/*
执行流程:
当前程序运行到while循环结构时,首先判断while之后的小括号里面的循环条件是否为true,如果为true,执行循环体,在回到循环条件判断,直到循环条件为false,终止循环!!!
*/
/*
一周七天
吃饭睡觉打豆豆
期望执行的循环次数为7次
1
<= 7
< 8
*/
class Demo6 {
public static void main(String[] args) {
// 定义一个循环使用的变量,int整数类型
// 变量名 i,初始化数据为1
int i = 1;
/*
循环操作中如果循环使用的变量没有变更,是存在
可能当前循环成为一个【无限循环】,Ctrl + C
*/
while (i <= 7) {
System.out.println(i + ":吃饭睡觉打豆豆");
// 循环条件变更,修改循环使用的变量
i += 1; // i++; ++i;
}
System.out.println("i = " + i);
}
}
/*
while循环结构
展示数值 1 ~ 100
*/
class Demo7 {
public static void main(String[] args) {
// 定义循环使用的变量,int类型,初始化为1
// 循环使用的变量名 i
int i = 1;
while (i <= 100) {
System.out.println("i : " + i);
i += 1;
}
}
}
/*
while 循环结构
展示数值 1 ~ 100 所有数值的和
*/
class Demo8 {
public static void main(String[] args) {
// 循环使用的变量,int类型,变量名 i 初始化为 1
int i = 1;
// 保存1 ~ 100相加之和的变量 sum
int sum = 0;
// 利用while循环
while (i <= 100) {
sum += i;
i += 1;
}
System.out.println("Sum : " + sum);
// 利用循环可以解决问题,但是在开发中是需要使用一些数学公式
// 来提高我们的开发效率
System.out.println((1 + 100) * 50);
}
}
2.3 do - while循环
/*
```java
/*
使用do - while循环,展示1 ~ 100 所有的偶数
*/
class Demo9 {
public static void main(String[] args) {
/*
定义一个循环变量 i. int数据类型,初始化为1
*/
int i = 1;
/*
循环执行 100次
if分支结构判断执行 100次
总时间 200单位时间
*/
do {
// 嵌套了一个if分支,条件判断
if (i % 2 == 0) {
System.out.println("i = " + i);
}
i += 1;
} while (i <= 100);
System.out.println("--------------------------");
int j = 2;
/*
循环执行 50 次
总时间 50单位时间
*/
do {
System.out.println("j = " + j);
j += 2;
} while (j <= 100);
}
}
/*