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.- לLoop את
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. · לחץ על הרץ כדי לראות את התוצא כאן.