AP计算机教程5-3:for循环
当循环的执行次数比较明确时,for
循环是一个优先选择。for
循环有三个部分:初始化、条件和变化。这些部分由;
分隔标示,且都是可选的(当然for(;;)
和while(true)
一样就是我们之前提到的无限循环了),不过两个;
必须都出现。
for(initialization; condition; change)
for
循环的一个独特特点是括号中的代码并不在所在的位置执行。初始化代码仅在循环开始前执行一次;在每轮循环开始前会检查条件,如果为true
则继续循环(在一开始条件就为false
的情况下,循环则根本不执行);在每轮循环结束后执行一次变化的部分。在条件为false
、循环结束后,程序将继续执行循环体之后的语句。
比较for
循环和while
循环,你很容易会发现两者在某种意义上是等价的。只要把初始化和变化的部分移到相应位置,即可将for
循环改写成while
循环。
试着运行下面代码,看看会发生什么?把第11行的i = 5
改成i = 3
呢?
public class SongTest { public static void printPopSong() { String line1 = " bottles of pop on the wall"; String line2 = " bottles of pop"; String line3 = "Take one down and pass it around"; // loop 5 times (5, 4, 3, 2, 1) for (int i = 5; i > 0; i--) { System.out.println(i + line1); System.out.println(i + line2); System.out.println(line3); System.out.println((i - 1) + line1); System.out.println(); } } public static void main(String[] args) { SongTest.printPopSong(); } }
printPopSong
method会打印歌词。循环先会将i
赋值为5
,然后检查i
是否大于0
。因为5
比0
大,循环即开始执行。在每次新检查之前,i
的值会减小1
。当i
值变为0
时,循环停止执行。
循环执行次数可以通过公式largestValue - smallestValue + 1
计算。largestValue
指的是循环条件为true
的最大值,smallestValue
指的是循环条件为true
的最小值。对于以上代码而言,最大值为5
而最小值为1
,故循环共执行五次,即在i
在取5, 4, 3, 2, 1
这些值时。当i
减到0
时,条件变为false
,循环结束并继续执行循环体之后的语句。
0:00
What does the following code print?
for (int i = 3; i < 8; i++) { System.out.print(i + " "); }
i
值为3
,i
值最后会变为8
,但此时打印i
的循环体并不会被执行,因而输出的最大数是7
。What does the following code print?
for (int i = 1; i <= 10; i++) { System.out.print(i + " "); }
i <= 10
,故10
可被循环体中的语句打印。How many times does the following method print a *
?
for (int i = 3; i <= 9; i++) { System.out.print("*"); }
<
的话则是\(8-3+1=6\)。
0 条评论