- 零基础Java学习笔记
- 明日科技编著
- 1484字
- 2025-02-20 06:58:12
3.5 循环语句

循环语句用于重复执行某段程序代码,直到满足特定条件为止。在Java 中,循环语句有3 种形式:for 循环语句、while 循环语句和do…while 循环语句。
3.5.1 for 循环语句
for 循环语句是非常常用的循环语句,一般用于循环次数已知的情况下。它的一般形式为:

●初始化语句:初始化循环体变量。
●循环条件:起决定性作用,用于判断是否继续执行循环体。其值是boolean 型的表达式,即结果只能是true 或false。
●迭代语句:用于改变循环条件的语句。
●语句序列:该语句序列被称为循环体,当循环条件的结果为true 时,会重复执行它。
for 循环语句的流程:首先执行初始化语句,然后判断循环条件,当循环条件为true 时,就执行一次循环体,最后执行迭代语句,改变循环变量的值。这样就是一次循环。接下来进行下一次循环,直到循环条件的值为false 时,结束循环。
for 循环语句执行流程如图3.17 所示。
【例3.7】 使用for 循环语句实现打印1 ~10 的所有整数,具体代码如下:

程序运行结果如图3.18 所示。

图3.17 for 循环语句执行流程

图3.18 for 循环语句实现打印的结果
学习笔记
千万不要让程序无止境地执行,否则会造成死循环。
例如,每执行一次i++,i 就会加1,永远满足循环条件。这个循环永远不会终止,具体代码如下:

3.5.2 while 循环语句
while 循环语句是用一个表达式来控制循环的语句。它的一般形式为:

●表达式:用于判断是否执行循环,其值必须为boolean 型,也就是说,其结果只能为true 或false。当循环开始时,首先会执行表达式,如果表达式的值为true,则会执行语句序列,也就是循环体;然后当到达循环体的末尾时,会再次执行表达式,直到表达式的值为false,才会开始执行循环语句后面的语句。
while 循环语句执行流程如图3.19 所示。
【例3.8】 使用while 循环语句计算1 ~99 的整数和,具体代码如下:

程序运行结果如图3.20 所示。

图3.19 while 循环语句执行流程

图3.20 while 循环语句的计算结果
学习笔记
一定要保证程序正常结束,否则会造成死循环。
例如,0 永远都小于100,在运行以下代码后,程序将会不停地输出0:

3.5.3 do…while 循环语句
do…while 循环语句被称为后测试循环语句,它使用一个条件来控制是否继续重复执行该语句。它的一般形式为:

do…while 循环语句的执行过程与while 循环语句有所区别。do…while 循环至少会被执行一次,它首先执行循环体的语句序列,然后判断是否继续执行。
do…while 循环语句执行流程如图3.21 所示。
【例3.9】 使用do…while 循环语句计算1 ~100 的整数和,具体代码如下:

程序运行结果如图3.22 所示。

图3.21 do…while 循环语句执行流程

图3.22 do…while 循环语句的计算结果
在一般情况下,如果while 和do…while 循环语句的循环体相同,它们的输出结果就相同;但是,如果while 后面的表达式的值一开始就是false,它们的输出结果就不同。
例如,在while 和do…while 循环语句的循环体相同且表达式的值为false的情况下,具体代码如下:

程序运行结果如图3.23 所示。

图3.23 while 和do…while 循环语句的运行结果
学习笔记
在使用do…while 循环语句时,一定要保证循环能够正常结束,否则会造成死循环。
例如,0 永远都小于100,在运行以下代码后,就会造成死循环:

3.5.4 循环的嵌套
循环的嵌套就是在一个循环体内可以包含另一个完整的循环体,而在这个完整的循环体内还可以包含其他的循环体。循环嵌套很复杂,在for 循环语句、while 循环语句和do…while 循环语句中都可以进行嵌套,并且在它们之间也可以相互嵌套。下面是几种嵌套的形式。
1.for 循环语句的嵌套
一般形式为:

2.while 循环语句的嵌套
一般形式为:

3.do…while 循环语句的嵌套
一般形式为:

4.for 循环语句与while 循环语句的嵌套
一般形式为:


5.while 循环语句与for 循环语句的嵌套
一般形式为:

6.do…while 循环语句与for 循环语句的嵌套
一般形式为:

为了使读者更好地理解循环语句的嵌套,下面以一个实例来说明。
【例3.10】 打印九九乘法表,具体代码如下:

程序运行结果如图3.24 所示。

图3.24 打印九九乘法表