נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
12
חלקPart 2: מתודות ומערכיםMethods & arrays כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

חריגות בסיסיותBasic exceptions

מה זו חריגה, try, catch ו-finally, זריקה עם throw, והודעות שגיאה שעוזרות.

What an exception is, try, catch and finally, throwing with throw, and error messages that help.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-IntelliJ ולסמן פתרתי. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in IntelliJ and mark I solved it. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. מה ידפיס הקוד?What does it print?
main
try {
    System.out.println("A");
    int x = 1 / 0;
    System.out.println("B");
} catch (ArithmeticException e) {
    System.out.println("C");
}
System.out.println("D");

2. מתי רץ בלוק finally?When does a finally block run?

3. איזו שורה זורקת חריגה?Which line throws an exception?

תרגיליםExercises

תרגילExercise 1

המרה עם ברירת מחדלParse with a fallback

כתבו static int parseOr(String s, int fallback) שמחזירה את המספר, או את fallback אם הטקסט אינו מספר. הדפיסו parseOr("42", 0) + " " + parseOr("4x", -1): 42 -1.

Write static int parseOr(String s, int fallback) returning the number, or fallback if the text isn't a number. Print parseOr("42", 0) + " " + parseOr("4x", -1): 42 -1.

איך הפלט אמור להיראות?What should the output look like?
42 -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: return גם בתוך ה-try וגם בתוך ה-catch.A return inside both the try and the catch.
לפתרוןSolution
תרגילExercise 2

ממוצע של כלוםAverage of nothing

עם מערך ציונים ריק התוכנית קורסת. צפו ב"איפה זה נשבר", ועטפו את החילוק ב-try/catch כך שיודפס No grades.

With an empty grades array the program crashes. Watch "where it breaks", and wrap the division in try/catch so it prints No grades.

איך הפלט אמור להיראות?What should the output look like?
No grades
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: catch (ArithmeticException e)catch (ArithmeticException e)
רמזHint 2: אפשר גם if (grades.length == 0). כאן מתרגלים try/catch.An if (grades.length == 0) also works. Here we practise try/catch.
לפתרוןSolution
תרגילExercise 3

גיל לא חוקיAn illegal age

כתבו static void checkAge(int age) שזורקת IllegalArgumentException("Bad age: " + age) כשהגיל מחוץ ל-0 עד 120. ב-main, בתוך try: בדקו 30 (הדפיסו 30 is fine), ואז -3. ב-catch הדפיסו Error: ואת ההודעה.

Write static void checkAge(int age) that throws IllegalArgumentException("Bad age: " + age) when the age is outside 0 to 120. In main, inside a try: check 30 (print 30 is fine), then -3. In the catch print Error: and the message.

איך הפלט אמור להיראות?What should the output look like?
30 is fine
Error: Bad age: -3
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: throw new IllegalArgumentException("Bad age: " + age);throw new IllegalArgumentException("Bad age: " + age);
רמזHint 2: e.getMessage()e.getMessage()
לפתרוןSolution
תרגילExercise 4

הסדר של 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.
לפתרוןSolution
תרגילExercise 5

שואלים עד שמקבלים מספרAsk until you get a number

קראו שורות מהקלט עד שמגיע מספר. על כל שורה שאינה מספר הדפיסו Not a number: ..., ועל המספר Got ... וסיימו. עם הקלט abc ואז 12 יודפס Not a number: abc ואז Got 12.

Read input lines until a number arrives. For every line that isn't a number print Not a number: ..., and for the number print Got ... and stop. With the input abc then 12 it prints Not a number: abc then Got 12.

איך הפלט אמור להיראות?What should the output look like?
abc
Not a number: abc
12
Got 12
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: while (true) עם break אחרי הצלחה.while (true) with a break after success.
רמזHint 2: in.nextLine() בתוך הלולאה, ו-parseInt בתוך try.in.nextLine() inside the loop, and parseInt inside a try.
לפתרוןSolution
תרגילExercise 6

מדף, צעד 12: שנה לא חוקית לא מפילהShelf, step 12: a bad year doesn't crash

פרויקט מלווהCompanion project

שורות בפורמט Title;Year: Dune;1965, Emma;18x5, Ulysses;1922. הדפיסו כל ספר תקין כמו Dune (1965). על שנה לא חוקית הדפיסו Skipping Emma: bad year 18x5 והמשיכו. בסוף Valid books: 2.

Lines as Title;Year: Dune;1965, Emma;18x5, Ulysses;1922. Print each valid book like Dune (1965). For an illegal year print Skipping Emma: bad year 18x5 and go on. Finally Valid books: 2.

איך הפלט אמור להיראות?What should the output look like?
Dune (1965)
Skipping Emma: bad year 18x5
Ulysses (1922)
Valid books: 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: line.split(";") נותן [title, year].line.split(";") gives [title, year].
רמזHint 2: ה-try בתוך הלולאה, כדי שספר אחד רע לא יעצור את כולם.The try goes inside the loop, so one bad book doesn't stop all of them.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

שני catchTwo catches

כתבו static String safeGet(int[] a, String index) שממירה את האינדקס ומחזירה את הערך כמחרוזת. אם האינדקס אינו מספר: not a number; אם הוא מחוץ למערך: bad index. עבור {10, 20, 30} עם "1", "9", "x": 20, bad index, not a number.

Write static String safeGet(int[] a, String index) converting the index and returning the value as a string. If the index isn't a number: not a number; if it's outside the array: bad index. For {10, 20, 30} with "1", "9", "x": 20, bad index, not a number.

איך הפלט אמור להיראות?What should the output look like?
20
bad index
not a number
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: try אחד, ושני בלוקי catch אחד אחרי השני.One try, and two catch blocks one after the other.
רמזHint 2: "" + a[i] הופך מספר למחרוזת."" + a[i] turns a number into a string.
לפתרוןSolution
אתגרChallenge 2

הודעות שגיאה שעוזרותError messages that help

כתבו static int minutes(String time) שממירה HH:MM לדקות מתחילת היום. אם אין בדיוק נקודתיים אחד, זרקו Bad time: 7 (use HH:MM). אם השעה מחוץ ל-0 עד 23, זרקו Bad time: 25:00 (hour must be 0-23). עבור 09:30, 25:00, 7 הדפיסו את הדקות, או Error: ואת ההודעה: 570, Error: Bad time: 25:00 (hour must be 0-23), Error: Bad time: 7 (use HH:MM).

Write static int minutes(String time) converting HH:MM to minutes since midnight. Without exactly one colon, throw Bad time: 7 (use HH:MM). With an hour outside 0 to 23, throw Bad time: 25:00 (hour must be 0-23). For 09:30, 25:00, 7 print the minutes, or Error: and the message: 570, Error: Bad time: 25:00 (hour must be 0-23), Error: Bad time: 7 (use HH:MM).

איך הפלט אמור להיראות?What should the output look like?
570
Error: Bad time: 25:00 (hour must be 0-23)
Error: Bad time: 7 (use HH:MM)
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: time.split(":") ובודקים parts.length.time.split(":") and check parts.length.
רמזHint 2: ההודעה כוללת את הקלט ואת מה שצפוי: כך מי שרואה אותה יודע מה לתקן.The message includes the input and what's expected: then whoever sees it knows what to fix.
לפתרוןSolution

נבנה על ידיBuilt by Ariel Yohimovich