Strings and nested loops · String dan perulangan bersarang
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 dan perulangan bersarang
- Sebuah
Stringadalah baris karakter, masing-masing memiliki posisi (indeks). - Indeks pertama adalah
0, dan yang terakhir adalahlength() - 1. - Dalam pelajaran ini Anda menelusuri String satu karakter pada satu waktu, dan menaruh perulangan di dalam perulangan.
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.
Menelusuri String
s.length()memberikan jumlah karakter.s.charAt(i)memberikan karakter pada indeksi.- Loop
idari0hinggalength() - 1untuk mengunjungi setiap karakter.
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).
Menghitung karakter
- Anda dapat menghitung berapa kali sebuah karakter muncul.
- Gunakan counter yang dimulai dari
0. - Satu karakter menggunakan tanda petik tunggal, seperti
'o'. Bandingkan dengan==(chars, bukan String).
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.
Membangun String baru
- Mulai dengan String kosong
""dan tambahkan karakter dengan+. - Membaca dari akhir ke awal membalik String.
- Setiap
+membuat String yang lebih panjang.
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.
Enhanced for (pratinjau)
- Untuk menelusuri String Anda biasanya perlu indeks, jadi normal
foradalah yang terbaik. - Tapi Java juga memiliki perulangan enhanced for yang mengunjungi item secara langsung.
- Anda akan menggunakannya banyak dengan array dalam pelajaran 8. Berikut pratinjau kecil dengan teks.
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.
Perulangan bersarang
- Sebuah perulangan bersarang adalah perulangan di dalam perulangan lain.
- Perulangan dalam berjalan seluruhnya untuk setiap langkah perulangan luar.
- Di bawah ini, perulangan luar memilih baris, dan perulangan dalam mencetak bintang di baris itu.
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.
Kesalahan umum
- String bersifat tidak dapat diubah — simpan hasil
s.substring(...)dll. s.length()adalah method (dengan()), berbeda dengan.lengtharray.
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.
Sekarang Anda coba
- Setiap tugas telah mengisi kerangka class — tulis kode Anda di dalam main, atau lengkapi method yang ditampilkan.
- Tekan Jalankan untuk mengompilasi dan menjalankan, lalu Periksa jawaban.
- Kode Anda dikompilasi dan dijalankan di server, sehingga bahkan jalankan pertama kali pun cepat.
Indexing a String · Indeksasi String
Each char has an index from 0; substring takes a range. · Setiap karakter memiliki indeks dari 0; substring mengambil rentang.
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. · Lengkapi countChar(String s, char c) agar mengembalikan berapa kali c muncul dalam s. Gunakan charAt dan ==. Sebagai contoh countChar("balloon", 'o') adalah 2.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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 +. · Lengkapi reverse(String s) agar mengembalikan s dengan huruf-huruf dalam urutan terbalik. Sebagai contoh reverse("code") adalah "edoc". Bangun String baru dengan +.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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. · Gunakan perulangan bersarang untuk mencetak segitiga bintang: baris 1 memiliki satu *, baris 2 memiliki dua, baris 3 memiliki tiga, baris 4 memiliki empat. Cetak setiap baris dengan System.out.println.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.