3.2 循环语句使用方法及注意事项


3.2.1 while语句

格式:

	while(循环条件){
		循环体
	}	

注意:

  1. 当循环体只要一个语句时,可以省略花括号(不建议)
  2. 循环条件要有范围,不然会进入死循环
//while语句

public class Wh {
	public static void main(String[] args) {
		int i = 7;
		while (i < 10) {//循环条件限定了i的范围
			System.out.println("当前i的值为:" + i);
			i++;
		}
	}
}
结果为:
     	当前i的值为:7
		当前i的值为:8
		当前i的值为:9

3.2.2 do…while语句

格式:

	do{
		循环体
	}while(循环条件)

注意:

  1. do…while 语句循环至少执行一次,不满足循环条件也是
  2. while 与 do…while 的区别是:while先判断循环条件,再执行;do…while先执行一次循环体语句,再判断循环条件。
//while 语句与 do...while 语句的区别

public class DoWh {
	public static void main(String[] args) {
		int i = 7;
		while (i < 7) {
			System.out.println("while语句");//不执行
			i++;
		}
		do {
			System.out.println("do...while语句");//执行了
			i++;
		} while (i < 7);
	}
}

结果为:
		do...while语句

3.2.3 for语句及其嵌套

格式:

	for(初始化语句;条件表达式;循环变量控制){
		循环体
	}

注意:

  1. 语句的分号不能少,可以写成for ( ; ; ;),但是是死循环;
  2. 初始化语句只在第一次执行
  3. for语句可以嵌套使用,外循环执行1次,内循环执行n次(乘法口诀表)。
//for语句

public class Fo {	
	public static void main(String[] args) {
		for(int i=7;i<10;i++) {
			System.out.println("当前i的值为:" + i);
		}
	}
}

结果为:
        当前i的值为:7
		当前i的值为:8
		当前i的值为:9
//利用for语句的循环嵌套打印乘法口诀表

public class ChengFanKeJue {
	public static void main(String[] args) {
		for (int i = 1; i <= 9; i++) {			
			for (int j = 1; j <= i; j++) {				
				System.out.print(j + "*" + i + "=" + i * j + "\t");
			}
			System.out.println();
		}
	}
}

在这里插入图片描述


3.2.4 数组的for语句

格式:

	for(声明新变量:数组名){
		循环体
	}

注意

  1. 该语句是用来访问数组元素

  2. 声明的新变量数据类型必须与数组类型一致

//数组的for语句

public class ArrayFor {	
	public static void main(String[] args) {
		String name[]= {"张三","李四","王五","赵六"};
		for(String i:name) {
			System.out.println("当前输出的名字为:" + i);
		}
	}
}

结果为:
		当前输出的名字为:张三
		当前输出的名字为:李四
		当前输出的名字为:王五
		当前输出的名字为:赵六

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值