Strings and nested loops · Strings e laços aninhados
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.
Strings e laços aninhados
- Uma
Stringé uma fileira de caracteres, cada um com uma posição (índice). - O primeiro índice é
0, e o último élength() - 1. - Nesta aula você percorre uma String um caractere por vez, e coloca laços dentro de laços.
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.
Percorrendo uma String
s.length()dá o número de caracteres.s.charAt(i)dá o caractere no índicei.- Loop
ide0atélength() - 1para visitar cada caractere.
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).
Contando caracteres
- Você pode contar quantas vezes um caractere aparece.
- Use um contador que comece em
0. - Um único caractere usa aspas simples, como
'o'. Compare com==(chars, não Strings).
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.
Construindo uma nova String
- Comece com uma String vazia
""e adicione caracteres com+. - Ler do final para o início inverte a String.
- Cada
+cria uma String maior.
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 (visualização)
- Para percorrer uma String geralmente você precisa do índice, então um normal
foré melhor. - Mas Java também tem um laço enhanced for que visita os itens diretamente.
- Você usará isso muito com arrays na aula 8. Aqui está uma pequena visualização com texto.
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.
Laços aninhados
- Um laço aninhado é um laço dentro de outro laço.
- O laço interno roda todo o caminho para cada passo do laço externo.
- Abaixo, o laço externo escolhe uma linha, e o laço interno imprime estrelas nessa linha.
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.
Erros comuns
- Strings são imutáveis — armazene o resultado de
s.substring(...)etc. s.length()é um método (com()), diferentemente do.lengthde um array.
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.
Agora você tenta
- Cada tarefa pré-preenche a estrutura da classe — escreva seu código dentro do main, ou complete o método mostrado.
- Pressione Run para compilar e executar, depois Check answer.
- Seu código compila e roda no servidor, então até a primeira execução é rápida.
Indexing a String · Indexação de uma String
Each char has an index from 0; substring takes a range. · Cada caractere tem um índice a partir de 0; substring pega um intervalo.
Complete countChar(String s, char c) so it returns how many times c appears in s. Use charAt and · e ==. For example countChar("balloon", 'o') is 2. · Complete countChar(String s, char c) para que ele retorne quantas vezes c aparece em s. Use charAt e ==. Por exemplo countChar("balloon", 'o') é 2.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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 +. · Complete reverse(String s) para que ele retorne s com as letras na ordem oposta. Por exemplo reverse("code") é "edoc". Construa uma nova String com +.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Use nested loops · laços aninhados 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. · Use laços aninhados para imprimir um triângulo de asteriscos: a linha 1 tem um *, a linha 2 tem dois, a linha 3 tem três, a linha 4 tem quatro. Imprima cada linha com System.out.println.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.