循环结构
1 为什么要用循环
代码中一定存在需要循环出现的情况,如果不使用循环,会导致以下一些问题
1. 阅读性极差!!!
2. 维护性极差!!!
3. 代码冗余!!!
2. while循环
while (/* 循环条件 true or false */) {
// 循环体
// (循环条件变更)
}
/*
执行流程:
当前程序运行到while循环结构时,首先判断while之后的小括号里面的循环条件是否为true,如果为true,执行循环体,在回到循环条件判断,直到循环条件为false,终止循环!!!
*/
/*
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;
}
}
}
3 do - while循环
do {
// 循环体
// (循环条件变更)
} while (/* 循环条件判断 */);
/*
执行流程:
当程序执行到do - while循环结构时,首先执行一次循环体(循环条件变更),再来判断while中循环条件判断是否为true,如果为true,继续执行,如果为false,终止循环。
【注意】
1. while(condition);;;;;;;;;;;;;;;;;;;;;;;;;;; 这里英文分号
2. 执行do - while需要明确第一次循环会不会存在隐患
*/
/*
使用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);
}
}
4 循环和分支的嵌套
/*
使用do - while循环,完成一个点菜系统
1. 完成用户的点菜功能
2. 点菜之后输出总价
3. 用户指定方式退出
*/
import java.util.Scanner;
class Demo14 {
public static void main(String[] args) {
/*
这里需要一个变量 int类型,作为用户的选择
变量名 choose
*/
int choose = 0;
/*
计算得到总价格,int类型,变量名为 total
*/
int total = 0;
/*
准备一个Scanner类型的变量,用于从键盘上获取用户
输入的数据
*/
Scanner sc = new Scanner(System.in);
System.out.println("欢迎来到骚磊老酒馆");
System.out.println("1. 青岛啤酒 8RMB");
System.out.println("2. 野格 88RMB");
System.out.println("3. 江小白 25RMB");
System.out.println("4. 乌苏 6RMB");
System.out.println("5. 1664 18RMB");
System.out.println("6. 下单");
do {
choose = sc.nextInt();
switch (choose) {
case 1:
System.out.println("1. 青岛啤酒 8RMB");
total += 8;
break;
case 2:
System.out.println("2. 野格 88RMB");
total += 88;
break;
case 3:
System.out.println("3. 江小白 25RMB");
total += 25;
break;
case 4:
System.out.println("4. 乌苏 6RMB");
total += 6;
break;
case 5:
System.out.println("5. 1664 18RMB");
total += 18;
break;
case 6:
System.out.println("6. 下单");
break;
default:
System.out.println("选择错误");
break;
}
} while (choose != 6);
System.out.println("本场消费 : " + total);
}
}
总结
-
循环过程中最核心的内容就是循环变量,需要对于循环变量的执行的过程中数值变量完全掌握!!!如果无法明确循环的次数,循环变量的值,循环的过程,可以将循环代码中变量的变更过程记录。
-
循环过程中需要注意无限循环问题,控制无限循环问题的出现。一定要保证循环条件有效性或者代码中存在一个跳出循环的机制。
-
do while循环中,第一次循环体的执行是没有经过任何的条件判断的,需要注意!
【已知,可控】 -
while和do while循环结构是可以进行互换的。
-
然后在while和do while之间考虑使用的情况下,一般推荐使用while循环。但是不代表do while没有实际的使用效果。