JAVA 循环结构语句 for while do...while

为了更好的处理问题,除了顺序结构和条件判断结构语句,JAVA还提供了循环结构语句。

JAVA中主要有三种循环结构语句:
1.while循环
2.do…while循环
3.for循环


while循环

结构形式:

while( 布尔表达式 ) {
//循环内容
}

只要布尔表达式结果为true,那么循环会一直进行下去。

代码实例:

public class Demo01while {
   public static void main(String[] args) {
      int x = 10;
      while( x < 20 ) {
         System.out.print("value of x : " + x );
         x++;
         // System.out.print("\n");	// 换行
      }
   }
}

结果如下:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19


do…while循环

对于while循环来说,如果不满足条件,则不能进入循环。但是有时候处理问题,即使不满足条件,也需要执行一次,此时便用到了do…while循环。

do…while 循环和 while 循环相似,不同的是,
do…while 循环至少会执行一次

格式:
do {
//代码语句
}while(布尔表达式);

注意:布尔表达式在循环体的后面,所以语句块在检测布尔表达式之前已经执行了。 如果布尔表达式的值为 true,则语句块一直执行,直到布尔表达式的值为 false。
说白了,看到do…while格式后,便知道为什么该循环为什么至少执行一次了,因为while在do的后面,先执行do,然后再while布尔判断。

代码演示:

public class Demo02DoWhile {
	public static void main(String args[]) {
		int x = 100;
		
		do{
			System.out.println("value of x : " + x );
			x++;
			// System.out.println("\n");	// 换行
		}while( x < 20 );
		System.out.println("value of x : " + x );
	}
}

执行结果:
value of x : 100
value of x : 101

通过代码举例,我们可以看到执行结果,x=100不符合x<20,但是do…while循环却执行了do部分中的代码,执行了加一操作。


for循环

虽然while和do…while循环基本上可以处理大部分问题,但是for循环在很多循环中处理问题更加简单。

格式:
for(初始化表达式; 布尔表达式; 步进表达式) {
//代码语句
}

关于for循环要注意以下几点:

  • 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
  • 其次执行的便是布尔表达式,如果结果为true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
  • 执行一次循环之后,通过步进表达式更新循环控制变量。
  • 再次检测布尔表达式。循环执行上面的过程。

代码演示:

public class Demo03For {
	public static void main(String[] args) {
		for (int i = 1; i < 10; i++) {
			System.out.println("I am sorry!!!" + i);
		}
		System.out.println("程序停止");
	}
}

执行结果:
I am sorry!!! 1
I am sorry!!! 2
I am sorry!!! 3
I am sorry!!! 4
I am sorry!!! 5
I am sorry!!! 6
I am sorry!!! 7
I am sorry!!! 8
I am sorry!!! 9
程序停止



题目:求出1-100之间的偶数和。

for循环求和:

public class Demo04NumSum {
	public static void main(String[] args) {
		int sum = 0;	// sum是用来累加的存钱罐
		
		for (int i = 1; i <= 100; i++) {
			if (i % 2 == 0) {
				sum += i;
			}
		}
		System.out.println("结果为: " + sum);	// 2550
	}
}

while循环求和:

public class Demo04NumSum {
	public static void main(String[] args) {
		int sum = 0;	// sum依旧是累加的容器
		int i = 1;
		while (i <= 100) {
			if (i % 2 == 0) {
				sum += i;
			}
			i++; // 步进表达,循环更新
		}
		System.out.println("结果为: " + sum);	// 2550
	}
}

总结:不论是for循环,还是while循环,对于求和其实都比较简单,但是对于不同的问题,其实我们可以针对性的处理,比如上面求和的例子其实就是等差数列的求和,为什么我们不利用数学的思想呢,如果利用等差数列求和公式,程序是不是直接一步到位执行完毕,何必循环一百次呢。算法用处的最最简单举例。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值