כל יום תרגיל אחר מתוך הקורס, אותו תרגיל לכל מי שנכנס היום. פתרתם? קיבלתם 30 XP בונוס והרצף נשמר.
Every day a different exercise from the course, the same one for everyone who visits today. Solved it? You get a 30 XP bonus and keep your streak.
אתגר חדש בחצות.A new challenge at midnight.
התרגיל של היוםToday's exercise
מפגש 1Session 1
שלום, עולם (בגרסה שלכם)Hello, world (your version)
כתבו תוכנית שמדפיסה שתי שורות: ברכה עם השם שלכם, ומשפט על משהו שאתם אוהבים.
Write a program that prints two lines: a greeting with your name, and a sentence about something you love.
איך הפלט אמור להיראות?What should the output look like?
שלום, אני נועה!
אני אוהבת פיצה וטיולים
Hi, I am Noa!
I love pizza and hiking
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:כל שורת פלט היא System.out.println נפרדת.Each output line is a separate System.out.println.
רמזHint 2:טקסט תמיד בתוך מירכאות כפולות, וכל משפט נגמר ב-;.Text always goes inside double quotes, and each statement ends with ;.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
System.out.println("שלום, אני נועה!");
System.out.println("אני אוהבת פיצה וטיולים");
}
}
publicclass Main {
publicstaticvoidmain(String[] args) {
System.out.println("Hi, I am Noa!");
System.out.println("I love pizza and hiking");
}
}
פלטOutput
שלום, אני נועה!
אני אוהבת פיצה וטיולים
Hi, I am Noa!
I love pizza and hiking
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 1Session 1
print מול printlnprint vs println
הדפיסו את השורה 1 2 3 GO! בעזרת ארבע פקודות הדפסה: שלוש print ו-println אחת. אחר כך, בשורה נפרדת, הדפיסו done.
Print the line 1 2 3 GO! using four print commands: three print and one println. Then, on a separate line, print done.
איך הפלט אמור להיראות?What should the output look like?
1 2 3 GO!
done
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:print לא יורדת שורה, אז הרווחים צריכים להיות בתוך הטקסט: "1 ".print doesn't move to a new line, so the spaces go inside the text: "1 ".
רמזHint 2:את ה-GO! מדפיסים עם println, ואז done כבר יופיע בשורה חדשה.Print GO! with println, and then done lands on a new line.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 2Session 2
צייד באגים: הממוצע שנעלםBug hunter: the vanishing half
הקוד אמור להדפיס 7.5, אבל מדפיס 7.0. אין שגיאה: זה באג לוגי. מצאו ותקנו.
The code should print 7.5 but prints 7.0. There's no error: it's a logic bug. Find it and fix it.
איך הפלט אמור להיראות?What should the output look like?
7.5
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:מה הטיפוס של (a + b) / 2? שני הצדדים int.What type is (a + b) / 2? Both sides are int.
רמזHint 2:החלוקה קורית לפני שהתוצאה נכנסת ל-double, ולכן החצי כבר אבד.The division happens before the result goes into the double, so the half is already lost.
רמזHint 3:מחלקים ב-2.0.Divide by 2.0.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
int a =7;
int b =8;
double avg = (a + b) /2.0;
System.out.println(avg);
}
}
פלטOutput
7.5
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 3Session 3
קבלה מיושרתAn aligned receipt
הדפיסו קבלה עם printf: שלוש שורות של מוצר ומחיר (Coffee 12.5, Cake 18.9, Juice 25), שם המוצר ברוחב 8 וצמוד לשמאל, המחיר ברוחב 7 עם 2 ספרות. בשורה האחרונה Total והסכום (שימו את המחירים במשתנים ותנו ל-Java לחבר).
Print a receipt with printf: three product-and-price lines (Coffee 12.5, Cake 18.9, Juice 25), the name 8 wide and left-aligned, the price 7 wide with 2 digits. On the last line Total and the sum (keep the prices in variables and let Java add them up).
איך הפלט אמור להיראות?What should the output look like?
Coffee 12.50
Cake 18.90
Juice 25.00
Total 56.40
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 4Session 4
שם היוםThe day's name
במשתנה day שימו 3. בעזרת switch עם חצים שמחזיר ערך, שמרו ב-name את שם היום (1 = Sunday … 7 = Saturday, אחרת Unknown) והדפיסו אותו.
Put 3 in day. With an arrow switch that returns a value, store the day's name in name (1 = Sunday … 7 = Saturday, otherwise Unknown) and print it.
איך הפלט אמור להיראות?What should the output look like?
Tuesday
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:String name = switch (day) { case 1 -> "Sunday"; ... default -> "Unknown"; };String name = switch (day) { case 1 -> "Sunday"; ... default -> "Unknown"; };
רמזHint 2:שימו לב לנקודה-פסיק אחרי הסוגר } של ה-switch.Mind the semicolon after the switch's closing }.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
int day =3;
String name =switch (day) {
case1->"Sunday";
case2->"Monday";
case3->"Tuesday";
case4->"Wednesday";
case5->"Thursday";
case6->"Friday";
case7->"Saturday";
default->"Unknown";
};
System.out.println(name);
}
}
פלטOutput
Tuesday
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 5Session 5
לוח הכפל של 7The 7 times table
הדפיסו 5 שורות: 7 x 1 = 7 עד 7 x 5 = 35.
Print 5 lines: 7 x 1 = 7 to 7 x 5 = 35.
איך הפלט אמור להיראות?What should the output look like?
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:System.out.println("7 x " + i + " = " + (7 * i));System.out.println("7 x " + i + " = " + (7 * i));
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
int n =7;
for (int i =1; i <=5; i++) {
System.out.println(n +" x "+ i +" = "+ (n * i));
}
}
}
פלטOutput
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 7Session 7
המקסימום מבין שלושהThe biggest of three
כתבו static int max(int a, int b), ואז static int max(int a, int b, int c) שמשתמשת בראשונה (overloading). הדפיסו max(4, 9, 6).
Write static int max(int a, int b), then static int max(int a, int b, int c) that uses the first one (overloading). Print max(4, 9, 6).
איך הפלט אמור להיראות?What should the output look like?
9
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:return a > b ? a : b;return a > b ? a : b;
publicclass Main {
staticint max(int a, int b) {
return a > b ? a : b;
}
staticint max(int a, int b, int c) {
return max(max(a, b), c);
}
publicstaticvoidmain(String[] args) {
System.out.println(max(4, 9, 6));
}
}
פלטOutput
9
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 8Session 8
הופכים מערךReversing an array
כתבו static void reverse(int[] a) שהופכת את המערך במקום (מחליפה את הראשון באחרון וכן הלאה). הדפיסו את {1, 2, 3, 4, 5} אחרי ההיפוך עם Arrays.toString.
Write static void reverse(int[] a) that reverses the array in place (swap first and last, and so on). Print {1, 2, 3, 4, 5} after reversing, with Arrays.toString.
איך הפלט אמור להיראות?What should the output look like?
[5, 4, 3, 2, 1]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:לולאה עד האמצע: for (int i = 0; i < a.length / 2; i++).Loop to the middle: for (int i = 0; i < a.length / 2; i++).
רמזHint 2:מחליפים את a[i] ואת a[a.length - 1 - i] עם משתנה זמני.Swap a[i] and a[a.length - 1 - i] with a temporary variable.
הפתרון שלנוOur solution
Main.java
import java.util.Arrays;
publicclass Main {
staticvoid reverse(int[] a) {
for (int i =0; i < a.length/2; i++) {
int t = a[i];
a[i] = a[a.length-1- i];
a[a.length-1- i] = t;
}
}
publicstaticvoidmain(String[] args) {
int[] n = {1, 2, 3, 4, 5};
reverse(n);
System.out.println(Arrays.toString(n));
}
}
פלטOutput
[5, 4, 3, 2, 1]
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 9Session 9
ספר טלפוניםPhone book
צרו HashMap<String, String> עם שני אנשי קשר (Noa → 050-1111111, Avi → 052-2222222). עדכנו את המספר של Noa ל-050-9999999, והדפיסו את המספר של Noa ואת getOrDefault("Dana", "unknown").
Create a HashMap<String, String> with two contacts (Noa → 050-1111111, Avi → 052-2222222). Update Noa's number to 050-9999999, and print Noa's number and getOrDefault("Dana", "unknown").
איך הפלט אמור להיראות?What should the output look like?
050-9999999
unknown
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:put עם מפתח קיים מחליף את הערך.put with an existing key replaces the value.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 10Session 10
צייד באגים: from a static contextBug hunter: from a static context
התוכנית לא מתקמפלת. צפו ב"איפה זה נשבר" בעמוד הפתרונות, ותקנו כך שתדפיס 25.
The program doesn't compile. Watch "where it breaks" on the solutions page, and fix it so it prints 25.
איך הפלט אמור להיראות?What should the output look like?
25
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:מה חסר בכותרת של square, שיש בכותרת של main?What's missing from square's header that main's header has?
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticint square(int x) {
return x * x;
}
publicstaticvoidmain(String[] args) {
System.out.println(square(5));
}
}
פלטOutput
25
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 11Session 11
מקסימום של שלילייםMax of negatives
max({-5, -2, -9}) מחזירה 0, שבכלל לא במערך. מצאו את הבאג ותקנו כך שיודפס -2.
max({-5, -2, -9}) returns 0, which isn't even in the array. Find the bug and fix it so it prints -2.
איך הפלט אמור להיראות?What should the output look like?
-2
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:מאיזה ערך best מתחיל? האם מספר שלילי יכול לעבור אותו?What value does best start at? Can a negative number beat it?
רמזHint 2:מתחילים מהאיבר הראשון: a[0].Start from the first item: a[0].
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticint max(int[] a) {
int best = a[0];
for (int x : a) {
if (x > best) {
best = x;
}
}
return best;
}
publicstaticvoidmain(String[] args) {
System.out.println(max(newint[]{-5, -2, -9}));
}
}
פלטOutput
-2
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 12Session 12
הסדר של finallyThe order of finally
הדפיסו start, ואז ב-try המירו את "x" למספר (והדפיסו parsed אחרי ההמרה). ב-catch הדפיסו bad, וב-finally done. הפלט: start, bad, done.
Print start, then in a try convert "x" to a number (printing parsed after the conversion). In the catch print bad, and in the finally done. The output: start, bad, done.
איך הפלט אמור להיראות?What should the output look like?
start
bad
done
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:parsed לא יודפס, כי ההמרה נכשלת לפניו.parsed won't print, because the conversion fails before it.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 14Session 14
תלמיד עם בנאיA student with a constructor
מחלקה Student עם בנאי Student(String name, int grade) ומתודה String info() (Noa: 95). צרו את Noa (95) ואת Avi (82) והדפיסו את שניהם.
A class Student with a constructor Student(String name, int grade) and a method String info() (Noa: 95). Create Noa (95) and Avi (82) and print both.
איך הפלט אמור להיראות?What should the output look like?
Noa: 95
Avi: 82
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:this.name = name;this.name = name;
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
Student s1 =new Student("Noa", 95);
Student s2 =new Student("Avi", 82);
System.out.println(s1.info());
System.out.println(s2.info());
}
}
class Student {
String name;
int grade;
Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
String info() {
return name +": "+ grade;
}
}
פלטOutput
Noa: 95
Avi: 82
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 15Session 15
מדחוםA thermometer
מחלקה Thermometer עם private double celsius, getCelsius(), getFahrenheit() (מחושב, בלי שדה), ו-setCelsius שזורקת IllegalArgumentException מתחת ל-273.15-. קבעו 25, הדפיסו 25.0C = 77.0F, נסו 300- (ב-catch הדפיסו Rejected: והודעה), והדפיסו שוב את הצלזיוס.
A class Thermometer with private double celsius, getCelsius(), getFahrenheit() (computed, no field), and setCelsius throwing IllegalArgumentException below -273.15. Set 25, print 25.0C = 77.0F, try -300 (in the catch print Rejected: and the message), and print the celsius again.
איך הפלט אמור להיראות?What should the output look like?
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 16Session 16
עובר או נכשלPass or fail
מחלקה Grade עם קבועים PASS = 56 ו-MAX = 100, ו-static String result(int score) שמחזירה pass, fail או invalid (מחוץ ל-0 עד MAX). הדפיסו עבור 90, 40, 130.
A class Grade with constants PASS = 56 and MAX = 100, and static String result(int score) returning pass, fail or invalid (outside 0 to MAX). Print for 90, 40, 130.
איך הפלט אמור להיראות?What should the output look like?
pass
fail
invalid
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:static final int PASS = 56;static final int PASS = 56;
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
System.out.println(Grade.result(90));
System.out.println(Grade.result(40));
System.out.println(Grade.result(130));
}
}
class Grade {
staticfinalint PASS =56;
staticfinalint MAX =100;
staticString result(int score) {
if (score <0|| score > MAX) {
return"invalid";
}
return score >= PASS ?"pass":"fail";
}
}
פלטOutput
pass
fail
invalid
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 17Session 17
toString לנקודהtoString for a point
הוסיפו ל-Point את toString שמחזירה (3, 4). הדפיסו את הנקודה לבד, בתוך מחרוזת (Point: (3, 4)), ובתוך רשימה: [(1, 2), (3, 4)].
Add a toString to Point returning (3, 4). Print the point alone, inside a string (Point: (3, 4)), and inside a list: [(1, 2), (3, 4)].
איך הפלט אמור להיראות?What should the output look like?
(3, 4)
Point: (3, 4)
[(1, 2), (3, 4)]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:@Override public String toString(): חייבת להיות public.@Override public String toString(): it must be public.
הפתרון שלנוOur solution
Main.java
import java.util.List;
publicclass Main {
publicstaticvoidmain(String[] args) {
Point p =new Point(3, 4);
System.out.println(p);
System.out.println("Point: "+ p);
System.out.println(List.of(new Point(1, 2), p));
}
}
class Point {
privatefinalint x;
privatefinalint y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@OverridepublicString toString() {
return"("+ x +", "+ y +")";
}
}
פלטOutput
(3, 4)
Point: (3, 4)
[(1, 2), (3, 4)]
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 18Session 18
ספר שמחזיק סופרA book that holds an author
כתבו את Author (שם, equals ו-hashCode לפי השם, toString שמחזיר את השם) ואת Book (כותר, Author, דירוג, getters, toString Dune (5)). הדפיסו Dune (5) by Herbert ואז true (הסופר שווה לסופר חדש באותו שם).
Write Author (a name, equals and hashCode by name, toString returning the name) and Book (a title, an Author, a rating, getters, toString Dune (5)). Print Dune (5) by Herbert then true (the author equals a new author with the same name).
איך הפלט אמור להיראות?What should the output look like?
Dune (5) by Herbert
true
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:השדה author ב-Book הוא מסוג Author, לא String.The author field in Book is of type Author, not String.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
publicclass Main {
publicstaticvoidmain(String[] args) {
Author herbert =new Author("Herbert");
Book dune =new Book("Dune", herbert, 5);
System.out.println(dune +" by "+ dune.getAuthor());
System.out.println(dune.getAuthor().equals(new Author("Herbert")));
}
}
class Shelf {
privatefinalList<Book> books =newArrayList<>();
void add(Book b) {
books.add(b);
}
}
class Book {
privatefinalString title;
privatefinal Author author;
privatefinalint rating;
Book(String title, Author author, int rating) {
this.title = title;
this.author = author;
this.rating = rating;
}
String getTitle() {
return title;
}
Author getAuthor() {
return author;
}
int getRating() {
return rating;
}
@OverridepublicString toString() {
return title +" ("+ rating +")";
}
}
class Author {
privatefinalString name;
Author(String name) {
this.name = name;
}
String getName() {
return name;
}
@Overridepublicbooleanequals(Object o) {
return o instanceof Author a && name.equals(a.name);
}
@Overridepublicint hashCode() {
return name.hashCode();
}
@OverridepublicString toString() {
return name;
}
}
פלטOutput
Dune (5) by Herbert
true
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 19Session 19
חיות מדברותTalking animals
ל-Animal יש name, מתודה sound() שמחזירה ..., ו-describe() שמחזירה Rex says Woof. כתבו Dog ו-Cat שיורשות ודורסות רק את sound. הדפיסו Rex says Woof ו-Mitzi says Meow.
Animal has a name, a method sound() returning ..., and describe() returning Rex says Woof. Write Dog and Cat that extend it and override only sound. Print Rex says Woof and Mitzi says Meow.
איך הפלט אמור להיראות?What should the output look like?
Rex says Woof
Mitzi says Meow
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:describe נשארת בהורה, ו-sound() שבתוכה מגיעה מהתת-מחלקה.describe stays in the parent, and the sound() inside it comes from the subclass.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 20Session 20
שכר לפי סוג עובדPay by employee type
abstract class Employee עם name ו-abstract int pay(). Hourly (תעריף × שעות) ו-Salaried (משכורת חודשית). במערך של Employee הדפיסו Noa: 5000 ו-Avi: 9000.
abstract class Employee with a name and abstract int pay(). Hourly (rate × hours) and Salaried (a monthly salary). In an Employee array print Noa: 5000 and Avi: 9000.
איך הפלט אמור להיראות?What should the output look like?
Noa: 5000
Avi: 9000
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:הלולאה לא יודעת איזה סוג עובד יש בכל תא, ולא צריכה לדעת.The loop doesn't know which kind of employee is in each cell, and doesn't need to.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 21Session 21
סך כל השטחיםTotal area
במערך Shape[] יש שני עיגולים (רדיוס 1 ו-2) ומלבן 2x3. חשבו בלולאה אחת את סך השטחים והדפיסו Total: 21.71.
A Shape[] array holds two circles (radius 1 and 2) and a 2x3 rectangle. Compute the total area in one loop and print Total: 21.71.
איך הפלט אמור להיראות?What should the output look like?
Total: 21.71
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:הלולאה קוראת ל-s.area(), וכל צורה עונה בעצמה.The loop calls s.area(), and each shape answers for itself.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
Shape[] shapes = {new Circle(1), new Rect(2, 3), new Circle(2)};
double total =0;
for (Shape s : shapes) {
total += s.area();
}
System.out.println(String.format("Total: %.2f", total));
}
}
abstractclass Shape {
abstractdouble area();
}
class Circle extends Shape {
privatefinaldouble r;
Circle(double r) {
this.r = r;
}
@Overridedouble area() {
returnMath.PI * r * r;
}
}
class Rect extends Shape {
privatefinaldouble w;
privatefinaldouble h;
Rect(double w, double h) {
this.w = w;
this.h = h;
}
@Overridedouble area() {
return w * h;
}
}
פלטOutput
Total: 21.71
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 22Session 22
ספירה גנריתA generic count
static <T> int count(List<T> list, T wanted) סופרת כמה איברים שווים (equals) ל-wanted. הדפיסו 3 עבור a ברשימה a, b, a, a, ו-2 עבור 2 ב-1, 2, 2.
static <T> int count(List<T> list, T wanted) counts how many items equal (equals) wanted. Print 3 for a in a, b, a, a, and 2 for 2 in 1, 2, 2.
איך הפלט אמור להיראות?What should the output look like?
3
2
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:<T> לפני טיפוס ההחזרה.<T> before the return type.
הפתרון שלנוOur solution
Main.java
import java.util.List;
publicclass Main {
static<T>int count(List<T> list, T wanted) {
int n =0;
for (T x : list) {
if (x.equals(wanted)) {
n++;
}
}
return n;
}
publicstaticvoidmain(String[] args) {
System.out.println(count(List.of("a", "b", "a", "a"), "a"));
System.out.println(count(List.of(1, 2, 2), 2));
}
}
פלטOutput
3
2
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 23Session 23
דירוג שבודק את עצמוA rating that checks itself
record Rating(int value) עם בנאי מקוצר שזורק Rating must be 1-5, got 9. הדפיסו Rating[value=4] ואז את ההודעה עבור 9.
record Rating(int value) with a compact constructor throwing Rating must be 1-5, got 9. Print Rating[value=4] then the message for 9.
איך הפלט אמור להיראות?What should the output look like?
Rating[value=4]
Rating must be 1-5, got 9
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:Rating { if (...) throw ...; }: בלי סוגריים אחרי השם.Rating { if (...) throw ...; }: no brackets after the name.
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
System.out.println(new Rating(4));
try {
new Rating(9);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
record Rating(int value) {
Rating {
if (value <1|| value >5) {
thrownewIllegalArgumentException("Rating must be 1-5, got "+ value);
}
}
}
פלטOutput
Rating[value=4]
Rating must be 1-5, got 9
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 24Session 24
Factory לצורותA shape factory
ShapeFactory.create(String kind, double size) מחזירה Circle או Square (records), וזורקת unknown shape: star (use circle or square) על סוג לא מוכר. הדפיסו 3.14, 9.0, ואת ההודעה.
ShapeFactory.create(String kind, double size) returns a Circle or a Square (records), and throws unknown shape: star (use circle or square) for an unknown kind. Print 3.14, 9.0, and the message.
איך הפלט אמור להיראות?What should the output look like?
3.14
9.0
unknown shape: star (use circle or square)
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:switch על מחרוזת, עם default -> throw ....A switch on a string, with default -> throw ....
3.14
9.0
unknown shape: star (use circle or square)
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 25Session 25
משימות לפי עדיפותTasks by priority
record Task(String name, int priority) implements Comparable<Task> (1 הכי דחוף). הכניסו ל-PriorityQueue שלוש משימות והוציאו עד שריק: fix server, write report, lunch.
record Task(String name, int priority) implements Comparable<Task> (1 is most urgent). Put three tasks in a PriorityQueue and take them out until empty: fix server, write report, lunch.
איך הפלט אמור להיראות?What should the output look like?
fix server
write report
lunch
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:הדפסת PriorityQueue עצמו לא ממוינת; רק poll מוציא בסדר.Printing the PriorityQueue itself is not sorted; only poll comes out in order.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 26Session 26
צייד באגים: משתנה בתוך למבדהBug hunter: a variable inside a lambda
התוכנית מהתזכורת לא מתקמפלת. כתבו את הספירה בלולאה רגילה כך שיודפס 6.
The program from the refresher doesn't compile. Write the count as a plain loop so it prints 6.
איך הפלט אמור להיראות?What should the output look like?
6
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:for (String w : words) { total += w.length(); }for (String w : words) { total += w.length(); }
הפתרון שלנוOur solution
Main.java
import java.util.List;
publicclass Main {
publicstaticvoidmain(String[] args) {
List<String> words =List.of("a", "bb", "ccc");
int total =0;
for (String w : words) {
total += w.length();
}
System.out.println(total);
}
}
פלטOutput
6
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 27Session 27
מי כתב את זה?Who wrote it?
static String authorOf(List<Book> books, String title) עם findFirst, map ו-orElse("unknown"), בלי null ובלי if. הדפיסו Herbert ואז unknown.
static String authorOf(List<Book> books, String title) with findFirst, map and orElse("unknown"), no null and no if. Print Herbert then unknown.
איך הפלט אמור להיראות?What should the output look like?
Herbert
unknown
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:Optional<Book> b = ...findFirst(); return b.map(Book::author).orElse("unknown");Optional<Book> b = ...findFirst(); return b.map(Book::author).orElse("unknown");
הפתרון שלנוOur solution
Main.java
import java.util.List;
import java.util.Optional;
publicclass Main {
staticString authorOf(List<Book> books, String title) {
Optional<Book> b = books.stream().filter(x -> x.title().equals(title)).findFirst();
return b.map(Book::author).orElse("unknown");
}
publicstaticvoidmain(String[] args) {
List<Book> books =List.of(new Book("Emma", "Austen", 1815, 474, 4), new Book("Dune", "Herbert", 1965, 412, 5), new Book("Persuasion", "Austen", 1817, 249, 5), new Book("Ulysses", "Joyce", 1922, 730, 3));
System.out.println(authorOf(books, "Dune"));
System.out.println(authorOf(books, "Hamlet"));
}
}
record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
Herbert
unknown
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 28Session 28
מתי checked ומתי uncheckedWhen checked, when unchecked
setRating זורקת IllegalArgumentException (באג אצל מי שקרא), ו-find זורקת NotFoundException checked (מצב צפוי). הדפיסו:
rating 4 / bug in the caller: rating must be 1-5, got 9 / Dune by Herbert / expected situation: no book called Hamlet.
setRating throws IllegalArgumentException (a bug in the caller), and find throws a checked NotFoundException (an expected situation). Print:
rating 4 / bug in the caller: rating must be 1-5, got 9 / Dune by Herbert / expected situation: no book called Hamlet.
איך הפלט אמור להיראות?What should the output look like?
rating 4
bug in the caller: rating must be 1-5, got 9
Dune by Herbert
expected situation: no book called Hamlet
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:רק ל-find צריך throws בכותרת.Only find needs throws in its header.
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticvoid setRating(int r) {
if (r <1|| r >5) {
thrownewIllegalArgumentException("rating must be 1-5, got "+ r);
}
System.out.println("rating "+ r);
}
staticString find(String title) throws NotFoundException {
if (!title.equals("Dune")) {
thrownew NotFoundException("no book called "+ title);
}
return"Dune by Herbert";
}
publicstaticvoidmain(String[] args) {
setRating(4);
try {
setRating(9);
} catch (IllegalArgumentException e) {
System.out.println("bug in the caller: "+ e.getMessage());
}
try {
System.out.println(find("Dune"));
System.out.println(find("Hamlet"));
} catch (NotFoundException e) {
System.out.println("expected situation: "+ e.getMessage());
}
}
}
class NotFoundException extendsException {
NotFoundException(String message) {
super(message);
}
}
פלטOutput
rating 4
bug in the caller: rating must be 1-5, got 9
Dune by Herbert
expected situation: no book called Hamlet
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 29Session 29
שמירה כ-JSONSaving as JSON
toJson(List<Book>) בונה מערך JSON עם StringJoiner. שמרו ל-shelf.json, קראו בחזרה והדפיסו:
[{"title": "Dune", "rating": 5}, {"title": "Emma", "rating": 4}] ואז true 64.
toJson(List<Book>) builds a JSON array with a StringJoiner. Save to shelf.json, read it back and print:
[{"title": "Dune", "rating": 5}, {"title": "Emma", "rating": 4}] then true 64.
איך הפלט אמור להיראות?What should the output look like?
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 31Session 31
שני דובריםTwo speakers
שני threads: אחד מדפיס Noa 1 עד Noa 3, השני Avi 1 עד Avi 3 (מתודה say(name)). חכו לשניהם עם join והדפיסו done. הסדר בין Noa ל-Avi יכול להשתנות, אבל done תמיד אחרון.
Two threads: one prints Noa 1 to Noa 3, the other Avi 1 to Avi 3 (a say(name) method). Wait for both with join and print done. The order between Noa and Avi can change, but done is always last.
איך הפלט אמור להיראות?What should the output look like?
Noa 1
Noa 2
Noa 3
Avi 1
Avi 2
Avi 3
done
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
publicclass Main {
publicstaticvoidmain(String[] args) throws InterruptedException {
Thread a =newThread(() -> say("Noa"));
Thread b =newThread(() -> say("Avi"));
a.start();
b.start();
a.join();
b.join();
System.out.println("done");
}
staticvoid say(String name) {
for (int i =1; i <=3; i++) {
System.out.println(name +" "+ i);
}
}
}
פלטOutput
Noa 1
Noa 2
Noa 3
Avi 1
Avi 2
Avi 3
done
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 32Session 32
בלוק synchronizedA synchronized block
שני threads מוסיפים כל אחד 1000 מספרים ל-ArrayList משותפת. ArrayList לא בטוחה ל-threads: עטפו את ה-add ב-synchronized (lock) על עצם פרטי, והדפיסו תמיד 2000.
Two threads each add 1000 numbers to a shared ArrayList. ArrayList isn't thread-safe: wrap the add in synchronized (lock) on a private object, and always print 2000.
איך הפלט אמור להיראות?What should the output look like?
2000
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:private static final Object lock = new Object();private static final Object lock = new Object();
רמזHint 2:בלי הנעילה: פחות מ-2000, או אפילו ArrayIndexOutOfBoundsException.Without the lock: less than 2000, or even an ArrayIndexOutOfBoundsException.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
publicclass Main {
privatestaticfinalList<Integer> items =newArrayList<>();
privatestaticfinalObject lock =newObject();
publicstaticvoidmain(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i =0; i <1000; i++) {
synchronized (lock) {
items.add(i);
}
}
};
Thread a =newThread(job);
Thread b =newThread(job);
a.start();
b.start();
a.join();
b.join();
System.out.println(items.size());
}
}
פלטOutput
2000
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 33Session 33
צייד באגים: volatile לא מספיקBug hunter: volatile isn't enough
התוכנית מהתזכורת מאבדת עדכונים למרות volatile. תקנו עם מתודה static synchronized void inc() כך שתמיד יודפס 200000.
The program from the refresher loses updates despite volatile. Fix it with a static synchronized void inc() method so it always prints 200000.
איך הפלט אמור להיראות?What should the output look like?
200000
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:עם synchronized כבר לא צריך volatile: הנעילה נותנת גם נראות.With synchronized you no longer need volatile: the lock gives visibility too.
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticint count =0;
staticsynchronizedvoid inc() {
count++;
}
publicstaticvoidmain(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i =0; i <100000; i++) {
inc();
}
};
Thread a =newThread(job);
Thread b =newThread(job);
a.start();
b.start();
a.join();
b.join();
System.out.println(count);
}
}
פלטOutput
200000
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 35Session 35
סכום בארבעה חלקיםA sum in four parts
בריכה של 3 threads. ארבע משימות (Callable) סוכמות כל אחת 250 מספרים (1–250, 251–500 וכו'). אספו את ה-Futures, חברו, והדפיסו 500500.
A pool of 3 threads. Four tasks (Callables) each sum 250 numbers (1–250, 251–500 and so on). Collect the Futures, add, and print 500500.
איך הפלט אמור להיראות?What should the output look like?
500500
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:משתנים בתוך הלולאה (from, to) כדי שהלמבדה תוכל להשתמש בהם.Variables inside the loop (from, to) so the lambda can use them.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
publicclass Main {
publicstaticvoidmain(String[] args) throwsException {
ExecutorService pool =Executors.newFixedThreadPool(3);
List<Future<Long>> parts =newArrayList<>();
for (int p =0; p <4; p++) {
long from = p *250L+1;
long to = from +249;
parts.add(pool.submit(() -> {
long s =0;
for (long i = from; i <= to; i++) {
s += i;
}
return s;
}));
}
long total =0;
for (Future<Long> f : parts) {
total += f.get();
}
pool.shutdown();
System.out.println(total);
}
}
פלטOutput
500500
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 36Session 36
מלאי עם ReentrantLockStock with a ReentrantLock
מלאי 5000. שלושה threads מורידים כל אחד 1000 פעמים, כל הורדה בתוך lock.lock() ו-try/finally. הדפיסו stock 2000.
A stock of 5000. Three threads each decrement 1000 times, each decrement inside lock.lock() and try/finally. Print stock 2000.
איך הפלט אמור להיראות?What should the output look like?
stock 2000
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:Lock lock = new ReentrantLock();Lock lock = new ReentrantLock();
הפתרון שלנוOur solution
Main.java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
publicclass Main {
staticfinal Lock lock =newReentrantLock();
staticint stock =5000;
publicstaticvoidmain(String[] args) throws InterruptedException {
Runnable job = () -> {
for (int i =0; i <1000; i++) {
lock.lock();
try {
stock--;
} finally {
lock.unlock();
}
}
};
Thread[] ts =newThread[3];
for (int k =0; k < ts.length; k++) {
ts[k] =newThread(job);
ts[k].start();
}
for (Thread t : ts) {
t.join();
}
System.out.println("stock "+ stock);
}
}
פלטOutput
stock 2000
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 37Session 37
allOfallOf
לכל כותר משימה שמחשבת עמודים (אורך × 100). חכו לכולן עם CompletableFuture.allOf(...), ואז סכמו: total pages 1500.
A task per title computing pages (length × 100). Wait for them all with CompletableFuture.allOf(...), then sum: total pages 1500.
איך הפלט אמור להיראות?What should the output look like?
total pages 1500
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 39Session 39
Repository בזיכרוןAn in-memory Repository
כתבו interface BookRepository (save, findByAuthor, findByTitle שמחזירה Optional) ומימוש InMemoryBookRepository. שמרו שלושה ספרים, והדפיסו את הספרים של Austen ואז false עבור Hamlet.
Write interface BookRepository (save, findByAuthor, findByTitle returning an Optional) and an InMemoryBookRepository. Save three books, then print Austen's books and false for Hamlet.
איך הפלט אמור להיראות?What should the output look like?
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:המתודות במימוש חייבות public (הן מממשות interface).The implementing methods must be public (they implement an interface).
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
publicclass Main {
publicstaticvoidmain(String[] args) {
BookRepository repo =new InMemoryBookRepository();
repo.save(new Book("Emma", "Austen", 1815));
repo.save(new Book("Dune", "Herbert", 1965));
repo.save(new Book("Persuasion", "Austen", 1817));
System.out.println(repo.findByAuthor("Austen"));
System.out.println(repo.findByTitle("Hamlet").isPresent());
}
}
interface BookRepository {
void save(Book b);
List<Book> findByAuthor(String author);
Optional<Book> findByTitle(String title);
}
record Book(String title, String author, int year) {
}
class InMemoryBookRepository implements BookRepository {
privatefinalList<Book> rows =newArrayList<>();
publicvoid save(Book b) {
rows.add(b);
}
publicList<Book> findByAuthor(String author) {
List<Book>out=newArrayList<>();
for (Book b : rows) {
if (b.author().equals(author)) {
out.add(b);
}
}
returnout;
}
publicOptional<Book> findByTitle(String title) {
for (Book b : rows) {
if (b.title().equals(title)) {
returnOptional.of(b);
}
}
returnOptional.empty();
}
}
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 41Session 41
לפרק תשובהParsing a reply
המודל ענה בטקסט שבתוכו JSON. parse(reply) מוציאה רשימת Suggestion(title, score) בעזרת regex, ומחזירה רשימה ריקה כשאין JSON. הדפיסו [Suggestion[title=Dune, score=9], Suggestion[title=Emma, score=7]] ואז [].
The model answered with text containing JSON. parse(reply) pulls out a list of Suggestion(title, score) with a regex, and returns an empty list when there's no JSON. Print [Suggestion[title=Dune, score=9], Suggestion[title=Emma, score=7]] then [].
איך הפלט אמור להיראות?What should the output look like?
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:מודלים מוסיפים לפעמים טקסט מסביב: מחפשים את התבנית, לא מניחים שכל התשובה JSON.Models sometimes add text around it: look for the pattern, don't assume the whole reply is JSON.
הפתרון שלנוOur solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
publicclass Main {
record Suggestion(String title, int score) {
}
staticList<Suggestion> parse(String reply) {
List<Suggestion>out=newArrayList<>();
Matcher m = Pattern.compile("\\{\"title\": \"([^\"]+)\", \"score\": (\\d+)\\}").matcher(reply);
while (m.find()) {
out.add(new Suggestion(m.group(1), Integer.parseInt(m.group(2))));
}
returnout;
}
publicstaticvoidmain(String[] args) {
String reply ="Here you go: [{\"title\": \"Dune\", \"score\": 9}, {\"title\": \"Emma\", \"score\": 7}]";
System.out.println(parse(reply));
System.out.println(parse("Sorry, I can't help with that."));
}
}
Write the insertion sort from the refresher and sort {9, 3, 7, 3, 1}: [1, 3, 3, 7, 9].
איך הפלט אמור להיראות?What should the output look like?
[1, 3, 3, 7, 9]
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:מזיזים ימינה כל עוד a[j] > x.Shift right while a[j] > x.
הפתרון שלנוOur solution
Main.java
import java.util.Arrays;
publicclass Main {
staticvoid sort(int[] a) {
for (int i =1; i < a.length; i++) {
int x = a[i];
int j = i -1;
while (j >=0&& a[j] > x) {
a[j +1] = a[j];
j--;
}
a[j +1] = x;
}
}
publicstaticvoidmain(String[] args) {
int[] a = {9, 3, 7, 3, 1};
sort(a);
System.out.println(Arrays.toString(a));
}
}
פלטOutput
[1, 3, 3, 7, 9]
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 44Session 44
שמאלה ולמטהLeft and down
עם Input ו-Ship מהתזכורת: שלושה טיקים של חצי שנייה שמאלה, ואז טיק אחד למטה, במהירות 120 מ-(100, 100). הדפיסו -80.0, 160.0.
With Input and Ship from the refresher: three half-second ticks to the left, then one tick down, at speed 120 from (100, 100). Print -80.0, 160.0.
איך הפלט אמור להיראות?What should the output look like?
-80.0, 160.0
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1:in.left = true; ואחר כך in.left = false; in.down = true;in.left = true; then in.left = false; in.down = true;
הפתרון שלנוOur solution
Main.java
publicclass Main {
publicstaticvoidmain(String[] args) {
Input in =new Input();
Ship s =new Ship(100, 100, 120);
in.left =true;
for (int i =0; i <3; i++) {
s.update(in, 0.5);
}
in.left =false;
in.down =true;
s.update(in, 0.5);
System.out.println(s.x +", "+ s.y);
}
}
class Input {
boolean left, right, up, down, fire;
}
class Ship {
double x, y;
finaldouble speed;
Ship(double x, double y, double speed) {
this.x = x;
this.y = y;
this.speed = speed;
}
void update(Input in, double dt) {
if (in.left) {
x -= speed * dt;
}
if (in.right) {
x += speed * dt;
}
if (in.up) {
y -= speed * dt;
}
if (in.down) {
y += speed * dt;
}
}
}
פלטOutput
-80.0, 160.0
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מפגש 45Session 45
עיגוליםCircles
circles(x1, y1, r1, x2, y2, r2): מתנגשים אם המרחק בין המרכזים ≤ סכום הרדיוסים. בין (0,0) ל-(6,8) המרחק 10: עם רדיוסים 5+5 true, ועם 5+4 false.
circles(x1, y1, r1, x2, y2, r2): they collide if the distance between centres ≤ the sum of radii. Between (0,0) and (6,8) the distance is 10: with radii 5+5 true, with 5+4 false.
איך הפלט אמור להיראות?What should the output look like?
true false
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.