Strings and nested loops · 字符串与嵌套循环
Strings and nested loops
- A
Stringis a row of characters, each with a position (an index). - The first index is
0, and the last islength() - 1. - In this lesson you walk through a String one character at a time, and put loops inside loops.
字符串与嵌套循环
String是一排字符,每个字符都有一个位置(索引 index)。- 第一个索引是
0,最后一个是length() - 1。 - 在这节课里,你会一个字符一个字符地遍历字符串,并把循环放进循环里。
Traversing a String
s.length()gives the number of characters.s.charAt(i)gives the character at indexi.- Loop
ifrom0up tolength() - 1to visit every character.
遍历字符串
s.length()给出字符的数量。s.charAt(i)给出索引i处的字符。- 让
i从0循环到length() - 1,就能访问每一个字符。
public class Main {
public static void main(String[] args) {
String s = "code";
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
}
}
Counting characters
- You can count how many times a character appears.
- Use a counter that starts at
0. - A single character uses single quotes, like
'o'. Compare with==(chars, not Strings).
数字符的个数
- 你可以数一个字符出现了多少次。
- 用一个从
0开始的计数器。 - 单个字符用单引号,例如
'o'。用==来比较(比较的是字符 char,不是字符串)。
public class Main {
public static void main(String[] args) {
String s = "balloon";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'o') {
count++;
}
}
System.out.println(count); // 2
}
}
Building a new String
- Start with an empty String
""and add characters with+. - Reading from the end to the start reverses the String.
- Each
+makes a longer String.
构建一个新字符串
- 从一个空字符串
""开始,用+添加字符。 - 从末尾读到开头,就能把字符串倒过来。
- 每个
+都会生成一个更长的字符串。
public class Main {
public static void main(String[] args) {
String s = "code";
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result = result + s.charAt(i);
}
System.out.println(result); // edoc
}
}
Enhanced for (preview)
- For walking a String you usually need the index, so a normal
foris best. - But Java also has an enhanced for loop that visits items directly.
- You will use it a lot with arrays in lesson 8. Here is a small preview with text.
增强 for(预览)
- 遍历字符串时你通常需要索引,所以普通的
for最合适。 - 但 Java 还有一种增强 for(enhanced for)循环,它直接访问每个元素。
- 你会在第 8 课和数组一起大量使用它。这里用文字做一个小预览。
public class Main {
public static void main(String[] args) {
String[] words = {"hi", "there", "!"};
for (String word : words) {
System.out.println(word);
}
}
}
Nested loops
- A nested loop is a loop inside another loop.
- The inner loop runs all the way for each step of the outer loop.
- Below, the outer loop picks a row, and the inner loop prints stars in that row.
嵌套循环
- 嵌套循环(nested loop)是一个循环里面又有一个循环。
- 对于外层循环的每一步,内层循环都会完整地跑一遍。
- 在下面,外层循环挑选一行,内层循环在那一行里打印星号。
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
String line = "";
for (int col = 1; col <= row; col++) {
line = line + "*";
}
System.out.println(line);
}
}
}
Common mistakes
- Strings are immutable — store the result of
s.substring(...)etc. s.length()is a method (with()), unlike an array's.length.
常见错误
- 字符串不可变——要存下
s.substring(...)等的结果。 s.length()是方法(带()),不同于数组的.length。
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
现在轮到你
- 每个任务都已经填好了类的骨架 —— 把你的代码写在 main 里面,或者补全给出的方法。
- 按运行来编译并运行,然后按检查答案。
- 你的代码在服务器上编译并运行,所以第一次运行也很快。
Indexing a String · 字符串索引
Each char has an index from 0; substring takes a range · 范围 (range). · 每个字符有从 0 开始的索引;substring 取一段。
Complete countChar(String s, char c) so it returns how many times c appears in s. Use charAt and ==. For example countChar("balloon", 'o') is 2. · 完成 countChar(String s, char c),让它返回 c 在 s 中出现的次数。使用 charAt 和 ==。例如 countChar("balloon", 'o') 是 2。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete reverse(String s) so it returns s with the letters in the opposite order. For example reverse("code") is "edoc". Build a new String with +. · 完成 reverse(String s),让它返回字母顺序相反的 s。例如 reverse("code") 是 "edoc"。用 + 构建一个新字符串。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use nested loops to print a triangle of stars: line 1 has one *, line 2 has two, line 3 has three, line 4 has four. Print each line with System.out.println. · 用嵌套循环打印一个星号三角形:第 1 行有一个 *,第 2 行有两个,第 3 行有三个,第 4 行有四个。每行用 System.out.println 打印。
Click Run to see the output here. · 点击“运行”查看此处输出。