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.
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.
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).
public class Main {
public static void main(String[] args) {
String s = "see you at ten";
int spaces = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
spaces++;
}
}
System.out.println(spaces); // 3
System.out.println(spaces + 1); // 4 words
}
}
Building a new String
- Start with an empty String
""and add characters with+. - The loop can read in any order. Reading from the end to the start (
i--) builds the String backwards. - Each
+makes a longer String.
public class Main {
public static void main(String[] args) {
String s = "java";
String result = "";
for (int i = 0; i < s.length(); i++) {
result = result + s.charAt(i) + s.charAt(i);
}
System.out.println(result); // jjaavvaa
}
}
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.
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 builds that row of a times table. The inner body runs 3 × 5 = 15 times.
- For a triangle, the inner bound changes with the row (
col <= row) instead of staying fixed.
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
String line = "";
for (int col = 1; col <= 5; col++) {
line = line + (row * col) + " ";
}
System.out.println(line);
}
// 1 2 3 4 5
// 2 4 6 8 10
// 3 6 9 12 15
}
}
Common mistakes
- Strings are immutable — store the result of
s.substring(...)etc. s.length()is a method (with()), unlike an array's.length.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- For a complete program, Run compiles and runs it. For a method or class task, Check answer compiles your code with the supplied tests and shows the results.
- Your code compiles and runs on the server, so even the first run is fast.
Indexing a String
Each char has an index from 0; substring takes a jangkauannya.
Kesulitan 3/5 · 200 koin + bonus kecil pada penyelesaian pertama hari ini
Complete countChar(String s, char c) so it returns how many times c appears in s. Use charAt dan ==. For example countChar("balloon", 'o') adalah 2.
Klik Jalankan untuk melihat output di sini.
Kesulitan 3/5 · 200 koin + bonus kecil pada penyelesaian pertama hari ini
Complete reverse(String s) so it returns s with the letters in the opposite order. For example reverse("code") adalah "edoc". Build a new String with +.
Klik Jalankan untuk melihat output di sini.
Kesulitan 3/5 · 200 koin + bonus kecil pada penyelesaian pertama hari ini
Use perulangan bersarang 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.
Klik Jalankan untuk melihat output di sini.