Loops in Java
Java for AP CS A Lesson 4 1:52 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Every loop, in every language, needs the same three parts, and a while loop spreads them out where you can see them.
任何语言里的任何循环,都需要同样的三个部分, 而 while 循环把它们摊开,让你看得见。
A start: i is set to one, before the loop.
起点:在循环之前,把 i 设为 1。
A test: keep going while i is less than or equal to three.
条件:只要 i 小于等于 3 就继续。
And a change: i goes up by one inside the loop.
改变:在循环体里把 i 加 1。
Leave out the change and the test stays true for ever — the loop never ends.
漏掉那个"改变",条件就永远为真—— 这个循环就永远停不下来。
A for loop is the same loop with all three in the header, separated by semicolons.
for 循环就是同一个循环,只是把三个部分都写进了头部,用分号隔开。
Start, then test, then change — in that order, every time.
起点、条件、改变——每次都是这个顺序。
And i plus plus is just shorthand for i equals i plus one.
而 i++ 只是 i = i + 1 的简写。
Nothing new is happening; the parts have simply been gathered together, which makes it much harder to forget one.
没有任何新东西发生; 只是这几个部分被收拢到了一起, 这样就更难漏掉其中一个。
Accumulation means building an answer up step by step inside a loop.
累加的意思,是在循环里一步步把答案搭起来。
Here sum starts at zero, and the loop adds each number in turn — one, three, six, ten, fifteen.
这里 sum 从 0 开始,循环把每个数字依次加上去—— 1、3、6、10、15。
Watch the box climb.
看那个盒子往上爬。
Two details: sum plus-equals i is shorthand for sum equals sum plus i, and the accumulator has to be declared before the loop, or there is nothing to add to.
两个细节:sum += i 是 sum = sum + i 的简写, 而累加器必须在循环"之前"声明, 否则就没有东西可加了。
Four things to take with you.
带走四点。
One: every loop needs a start, a test and a change.
第一:每个循环都需要一个起点、一个条件和一个改变。
Two: a for loop puts all three in its header.
第二:for 循环把这三样都写在头部。
Three: set an accumulator before the loop, and add inside it.
第三:在循环之前设好累加器,在循环里面加。
Four: no change means the test never fails — an infinite loop.
第四:没有改变,条件就永远不会不成立——那就是死循环。
Now write some loops in the tasks below.
现在去下面的题里写几个循环。