如本例所示:
import java.util.*;
public class TestForLoop
{
public static void main(String args[])
{
int i = 0,s = 0;
for(i = 0;i <= 10;++i)
{
s += i;
System.out.print("In the loop,i = "+i);
System.out.println("/ts = "+s);
}
System.out.println("At the end of the loop:"+i);
}
}
在for循環中,定義先做第三個參數的運算,即例子中的i++;然後再進行第二個參數的判斷,即例子中的i<=10。
具體表現為,題目的運作結果為:
In the loop,i = 0 s = 0
In the loop,i = 1 s = 1
In the loop,i = 2 s = 3
In the loop,i = 3 s = 6
In the loop,i = 4 s = 10
In the loop,i = 5 s = 15
In the loop,i = 6 s = 21
In the loop,i = 7 s = 28
In the loop,i = 8 s = 36
In the loop,i = 9 s = 45
In the loop,i = 10 s = 55
At the end of the loop:11
一定要謹記這些文法的細節。今天犯了很嚴重的錯誤,謹記!