1while循环
while () {
}
class Demo7 {
public static void main(String[] args) {
int i = 1;
while (i <= 100) {
System.out.println("i : " + i);
i += 1;
}
}
}
2do - while循环结构
do {
} while ();
class Demo9 {
public static void main(String[] args) {
int i = 1;
do {
if (i % 2 == 0) {
System.out.println("i = " + i);
}
i += 1;
} while (i <= 100);
System.out.println("--------------------------");
int j = 2;
do {
System.out.println("j = " + j);
j += 2;
} while (j <= 100);
}
}
3循环嵌套
import java.util.Scanner;
class Demo13 {
public static void main(String[] args) {
int choose = 0;
int total = 0;
Scanner sc = new Scanner(System.in);
System.out.println("武松酒馆看一下");
System.out.println("1. 二锅头 8RMB");
System.out.println("2. 血腥玛丽 88RMB");
System.out.println("3. 茅台 2500RMB");
System.out.println("4. 乌苏 6RMB");
System.out.println("5. 1664 18RMB");
System.out.println("6. 下单");
while (choose != 6) {
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;
}
}
System.out.println("本场消费 : " + total);
}
}
【注】:此循环嵌套也可以使用do - while循环操作来实现
while 和 do - while的区别不大,但两者的循环次数在一定的情况下有不同。
while 在运行中有可能一次都不执行
do - while 在运行中必须执行一次
在特殊情况下运行时,一定要区分这两点欧
4总结
1. 循环过程中最核心的内容就是循环变量,需要对于循环变量的执行的过程中数值变量完全掌握!!!如果无法明确循环的次数,循环变量的值,循环的过程,可以将循环代码中变量的变更过程记录。
2. 循环过程中需要注意无限循环问题,控制无限循环问题的出现。一定要保证循环条件有效性或者代码中存在一个跳出循环的机制。
3. do while循环中,第一次循环体的执行是没有经过任何的条件判断的,需要注意!
【已知,可控】
4. while和do while循环结构是可以进行互换的。
5. 然后在while和do while之间考虑使用的情况下,一般推荐使用while循环。但是不代表do while没有实际的使用效果。