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— это строка символов, каждый из которых имеет позицию (индекс).- Первый индекс равен
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'. Сравните с==(символы, а не строки).
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-цикл, который посещает элементы напрямую.
- Вы будете часто использовать его с массивами в уроке 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.
Вложенные циклы
- Вложенный цикл — это цикл внутри другого цикла.
- Внутренний цикл выполняется полностью для каждого шага внешнего цикла.
- Ниже внешний цикл выбирает строку, а внутренний печатает звездочки в этой строке.
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 или дополните показанный метод.
- Нажмите Run (Выполнить), чтобы скомпилировать и запустить, затем Check answer (Проверить ответ).
- Ваш код компилируется и выполняется на сервере, поэтому даже первый запуск происходит быстро.
Indexing a String · Индексация строки
Each char has an index from 0; substring takes a 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. · Нажмите Запустить, чтобы увидеть результат здесь.