-
概述
循环语句可以在满足循环条件的情况下,反复执行某一段代码,这段被重复执行的代码被称为循环体语句,当反复执行这个循环体时,需要在合适的时候把循环判断条件修改为false,从而结束循环,否则循环将一直执行下去,形成死循环。 -
for循环
for(初始化表达式; 布尔表达式; 步进表达式){
循环体
}
控制台输出10次HelloWorld。
public class Main {
public static void main(String[] args) {
for(int x = 0; x < 10; x++) {
System.out.println("HelloWorld"+x);
}
}
}
使用循环,计算 1-100之间的偶数和
public class Main {
public static void main(String[] args) {
//定义一个初始化变量,记录累加求和,初始值为0
int num=0;
//利用for循环获取1‐100之间的数字
for (int a=1;a<=100;a++){
//判断获取的数组是奇数还是偶数
if (a % 2 ==0){
//如果是偶数就累加求和
num+=a;
}
}
//循环结束之后,打印累加结果
System.out.println("num:"+num);
}
}
打印结果:
num:2550
- while循环
初始化表达式
while(布尔表达式){
循环体
步进表达式
}
while循环输出10次HelloWorld
public class Main {
public static void main(String[] args) {
//while循环实现打印10次HelloWorld
//定义初始化变量
int a=1;
//循环条件<=10
while (a<=10){
System.out.println("HelloWorld");
//步进
a++;
}
}
}
while循环计算1-100之间的和
public class Main {
public static void main(String[] args) {
//使用while循环实现
//定义一个变量,记录累加求和
int num=0;
//定义初始化表达式
int a=1;
//使用while循环让初始化表达式的值变化
while (a<=100){
//累加求和
num += a;
//步进表达式改变变量的值
a++;
//打印求和的变量
System.out.println("num:"+num);
}
}
}
打印结果:
- do…while
初始化表达式1
do{
循环体3
步进表达式4
}while(布尔表达式2);
控制台输出10次HelloWorld
public class Main {
public static void main(String[] args) {
int a=1;
do {
System.out.println("HelloWorld");
a++;
}while (a<=10);
}
}
do…while循环的特点:无条件执行一次循环体,即使我们将循环条件直接写成false,也依然会循环一次。这样的循环具有一定的风险性。
- 循环语句的区别
for 和 while 的小区别:
1.控制条件语句所控制的那个变量,在 for循环结束后,就不能再被访问到了,而while循环结束还可以继续使用,如果你想继续使用,就用while,否则推荐使用for。原因是for循环结束,该变量就从内存中消失,能够提高内存的使用效率。
2.在已知循环次数的时候使用推荐使用 for,循环次数未知的时推荐使while。
- break–跳出语句
使用场景:终止 switch或者循环
1. 在选择结构 switch语句中
2. 在循环语句中
3. 离开使用场景的存在是没有意义的
public class Main {
public static void main(String[] args) {
for (int a=1;a<=10;a++){
//打印完两次HelloWorld之后结束循环
if (a == 3){
break;
}
System.out.println("helloworld"+a);
}
}
}
打印结果:
helloworld1
helloworld2
- continue–跳出语句
使用场景:结束本次循环,继续下一次的循环
public class Main {
public static void main(String[] args) {
for (int a=1;a<=10;a++){
//不打印第三次helloworld。
if (a == 3){
continue;
}
System.out.println("helloworld"+a);
}
}
}
打印结果:
helloworld1
helloworld2
helloworld4
helloworld5
helloworld6
helloworld7
helloworld8
helloworld9
helloworld10