Java循环结构(while循环、do…while循环、for循环),以及break、continue关键字的使用。
- while循环
while(布尔表达式){
//循环内容
//布尔表达式为true时,循环一直进行
}
public class First {
public static void main(String[] args) {
int x = 4; //初始化变量x
while(x < 10) { //满足x < 10循环一直进行
System.out.println(x); //换行打印x
x++; //实现x的自增运算
}
}
}
4
5
6
7
8
9
- do…while循环
do{
//循环内容
}while(布尔表达式);//布尔表达式为true时,循环一直进行
public class First {
public static void main(String[] args) {
int x = 4; //初始化变量x
do{
System.out.println(x); //换行打印x
x++; //实现x的自增运算
}while(x < 10); //满足x < 10循环一直进行
}
}
4
5
6
7
8
9
- for循环
for(初始化;布尔表达式;更新){
//循环内容
}
最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。执行一次循环后,更新循环控制变量。再次检测布尔表达式。循环执行上面的过程。
public class First {
public static void main(String[] args) {
for(int x = 4; x < 10; x=x + 1) {
System.out.println(x); //换行打印x
}
}
}
4
5
6
7
8
9
- break关键字的使用
就是添加 break; 这条语句,主要用在循环语句或者switch语句,用来跳出整个语句块。
public class First {
public static void main(String[] args) {
int [] numbers = {1, 2, 3, 4, 5, 12, 59};
for(int x : numbers ) {
// x 等于 12 时跳出循环
if( x == 12 ) {
break;
}
System.out.println( x );
}
}
}
1
2
3
4
5
- continue 关键字的使用
就是添加 continue; 这条语句,continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代中。
在 for 循环中,continue 语句使程序立即跳转到更新语句。
在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。
public class First {
public static void main(String[] args) {
int [] numbers = {1, 2, 3, 4, 5, 12, 59};
for(int x : numbers ) {
if( x == 12 ) {
continue;
}
System.out.println( x );
}
}
}
//剔除了12这个元素
1
2
3
4
5
59