2021-07-10

Java循环结构(while循环、do…while循环、for循环),以及break、continue关键字的使用。

  1. 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
  1. 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
  1. 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
  1. 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
  1. 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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值