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 条评论