Strings and nested loops · Chaînes et boucles imbriquées
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 et boucles imbriquées
- Un
Stringest une rangée de caractères, chacun ayant une position (un index). - Le premier index est
0, et le dernier estlength() - 1. - Dans cette leçon, vous parcourez une String caractère par caractère, et placez des boucles à l'intérieur d'autres boucles.
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.
Parcourir une String
s.length()donne le nombre de caractères.s.charAt(i)donne le caractère à l'indexi.- Bouclez
ide0jusqu'àlength() - 1pour visiter chaque caractère.
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).
Compter les caractères
- Vous pouvez compter combien de fois un caractère apparaît.
- Utilisez un compteur qui commence à
0. - Un seul caractère utilise des guillemets simples, comme
'o'. Comparez avec==(chars, pas 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.
Construire une nouvelle String
- Commencez avec une String vide
""et ajoutez des caractères avec+. - Lire de la fin vers le début inverse la String.
- Chaque
+crée une String plus longue.
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 (aperçu)
- Pour parcourir une String, vous avez généralement besoin de l'index, donc une normale
forest préférable. - Mais Java possède aussi une boucle enhanced for qui visite les éléments directement.
- Vous l'utiliserez beaucoup avec les tableaux dans la leçon 8. Voici un petit aperçu avec du texte.
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.
Boucles imbriquées
- Une boucle imbriquée est une boucle à l'intérieur d'une autre boucle.
- La boucle intérieure s'exécute totalement pour chaque étape de la boucle extérieure.
- Ci-dessous, la boucle extérieure sélectionne une ligne, et la boucle intérieure imprime des étoiles dans cette ligne.
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.
Erreurs courantes
- Les Strings sont immuables — stockez le résultat de
s.substring(...)etc. s.length()est une méthode (avec()), contrairement à un.lengthde tableau.
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.
À vous maintenant
- Chaque tâche préremplit le squelette de classe — écrivez votre code dans main, ou complétez la méthode montrée.
- Appuyez sur Exécuter pour compiler et exécuter, puis sur Vérifier la réponse.
- Votre code compile et s'exécute sur le serveur, donc même la première exécution est rapide.
Indexing a String · Indice d'une chaîne
Each char has an index from 0; substring takes a range. · Chaque caractère a un indice de 0 ; substring prend une plage.
Complete countChar(String s, char c) so it returns how many times c appears in s. Use charAt and · et ==. For example countChar("balloon", 'o') is 2. · Complétez countChar(String s, char c) pour qu'elle retourne combien de fois c apparaît dans s. Utilisez charAt et ==. Par exemple countChar("balloon", 'o') est 2.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
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 +. · Complétez reverse(String s) pour qu'elle retourne s avec les lettres dans l'ordre inverse. Par exemple reverse("code") est "edoc". Construisez une nouvelle chaîne avec +.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Use nested loops · boucles imbriquées 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. · Utilisez des boucles imbriquées pour afficher un triangle d'étoiles : la ligne 1 a une *, la ligne 2 en a deux, la ligne 3 en a trois, la ligne 4 en a quatre. Affichez chaque ligne avec System.out.println.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.