Strings and nested loops
Java for AP CS A Lesson 5 1:44 English narration · English + 中文 subtitles burned in
Chapters
Transcript
To go through a String you loop over its indexes and read one character at a time with charAt.
要走遍一个字符串,你就在它的索引上循环, 用 charAt 一次读一个字符。
Watch the index move along.
看那个索引一路走过去。
Now look at the test carefully: i less than length, not less than or equal.
现在仔细看那个条件:i 小于 length(),而不是小于等于。
The word has four characters and their indexes are zero, one, two, three — index four does not exist, and asking for it throws an exception.
这个词有四个字符,它们的索引是 0、1、2、3—— 索引 4 并不存在,去要它会抛出异常。
Something surprising about Java Strings: you cannot change one.
Java 字符串有一件让人意外的事:你没法"改"它。
So when you want a modified version, you build a new String, and it grows one piece at a time — empty, then j dash, then j dash a dash, and so on.
所以当你想要一个改过的版本时,你是在"造一个新的字符串", 而它是一小块一小块长起来的—— 先是空的,然后是 "j-",再是 "j-a-",依此类推。
Each pass makes a brand-new String; the old one is never edited.
每一轮都造出一个全新的字符串;旧的那个从来没被改动。
That is what immutable means.
这就是"不可变"的意思。
A nested loop is a loop inside a loop, and the thing to understand is how many times the inside runs.
嵌套循环就是循环里面套循环, 而要弄明白的是:里面那层到底跑了多少次。
The inner loop runs all the way through for every pass of the outer one.
外层每走一轮,内层都要从头到尾跑完一遍。
Three outer passes, four inner passes each — look at the grid, one square per pass.
外层三轮,每轮内层四次—— 看那张格子图,一格就是一轮。
The body runs twelve times in total.
循环体总共跑了 12 次。
Outer times inner, always.
永远是外层乘内层。
Four things to take with you.
带走四点。
One: a String's indexes run from zero to length minus 1.
第一:字符串的索引从 0 到"长度减 1"。
Two: use less-than length, never less-than-or-equal.
第二:用"小于 length()",绝不用"小于等于"。
Three: Strings are immutable, so you build a new one.
第三:字符串是不可变的,所以你要造一个新的。
Four: a nested loop runs outer times inner passes.
第四:嵌套循环跑的次数是外层乘内层。
Now walk some Strings in the tasks below.
现在去下面的题里走几个字符串。