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

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

דיבוג ב-IntelliJDebugging in IntelliJ

נקודות עצירה, Step Over ו-Step Into, צפייה במשתנים, קריאת stack trace ושיטה למציאת באגים.

Breakpoints, Step Over and Step Into, watching variables, reading a stack trace and a method for finding bugs.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • דיבאגר: כלי שמריץ את התוכנית לאט, עוצר איפה שביקשתם ומראה את ערכי המשתנים. ב-IntelliJ: הכפתור עם החיפושית (Debug) במקום ▶.debugger: A tool that runs the program slowly, stops where you asked and shows the variables' values. In IntelliJ: the bug button (Debug) instead of ▶.
  • נקודת עצירה: נקודה אדומה שמסמנים בלחיצה ליד מספר השורה. בהרצת Debug התוכנית נעצרת לפני השורה הזאת.breakpoint: A red dot you set by clicking next to a line number. In a Debug run the program stops before that line.
  • Step Over: מריץ את השורה הנוכחית כולה (גם אם יש בה קריאה למתודה) ועוצר בשורה הבאה. קיצור: F8.Step Over: Runs the current line completely (even if it calls a method) and stops at the next line. Shortcut: F8.
  • Step Into: נכנס לתוך המתודה שנקראת בשורה הנוכחית, כדי לראות מה קורה בתוכה. קיצור: F7.Step Into: Goes into the method called on the current line, to see what happens inside it. Shortcut: F7.

02קוראים stack trace מלמעלהRead a stack trace from the top

השורה הראשונה אומרת מה קרה (ArithmeticException: / by zero). השורות at אומרות איפה: העליונה היא המקום שבו זה נשבר, והבאות הן מי שקרא לו. מחפשים את השורה הראשונה מהקוד שלכם (Main.java:7) ומתחילים משם. שימו לב: הבאג האמיתי הוא שמישהו קרא ל-average עם מערך ריק.

The first line says what happened (ArithmeticException: / by zero). The at lines say where: the top one is where it broke, and the next ones are who called it. Find the first line from your code (Main.java:7) and start there. Note: the real bug is that someone called average with an empty array.

טעות נפוצהCommon mistake

קוראים stack trace מלמעלה

Read a stack trace from the top

Main.java
public class Main {
    static double average(int[] grades) {
        int sum = 0;
        for (int g : grades) {
            sum += g;
        }
        return sum / grades.length;
    }

    static void report(String name, int[] grades) {
        System.out.println(name + ": " + average(grades));
    }

    public static void main(String[] args) {
        report("Noa", new int[]{90, 80});
        report("Avi", new int[]{});
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Noa: 85.0
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Main.average(Main.java:7)
	at Main.report(Main.java:11)
	at Main.main(Main.java:16)
בעברית פשוטה: In plain words: / by zero ב-average (שורה 7), שנקראה מ-report (שורה 11), שנקראה מ-main (שורה 16). עם {}, grades.length הוא 0./ by zero in average (line 7), called from report (line 11), called from main (line 16). With {}, grades.length is 0.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03הסימולציה היא דיבאגרThe simulation is a debugger

"צפו בזה רץ" עושה בדיוק מה ש-Step Over עושה ב-IntelliJ: שורה אחרי שורה, עם הערכים של המשתנים. כאן הסכום יוצא 10 במקום 15. עקבו אחרי i: הוא אף פעם לא מגיע ל-5. התנאי צריך להיות i <= 5.

"Watch it run" does exactly what Step Over does in IntelliJ: line after line, with the variables' values. Here the sum comes out 10 instead of 15. Follow i: it never reaches 5. The condition should be i <= 5.

Main.java
public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i < 5; i++) {
            sum += i;
        }
        System.out.println("1+2+3+4+5 = " + sum);
    }
}
פלטOutput
1+2+3+4+5 = 10
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04הדפסות דיבוגDebug prints

כשאין דיבאגר בהישג יד, מדפיסים את המשתנים בתוך הלולאה. מסמנים את השורות ב-DEBUG כדי למצוא ולמחוק אותן אחר כך.

When there's no debugger at hand, print the variables inside the loop. Mark the lines with DEBUG so you can find and delete them later.

Main.java
public class Main {
    public static void main(String[] args) {
        int[] prices = {30, 45, 25};
        int total = 0;
        for (int i = 0; i < prices.length; i++) {
            total += prices[i];
            System.out.println("DEBUG i=" + i + " total=" + total);
        }
        System.out.println("Total: " + total);
    }
}
פלטOutput
DEBUG i=0 total=30
DEBUG i=1 total=75
DEBUG i=2 total=100
Total: 100
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

05טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.

These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.

טעות נפוצהCommon mistake

האות האחרונה

The last letter

Main.java
public class Main {
    static char last(String s) {
        return s.charAt(s.length());
    }

    public static void main(String[] args) {
        System.out.println(last("Java"));
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 4 out of bounds for length 4
	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
	at java.base/java.lang.String.checkIndex(String.java:4822)
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:46)
	at java.base/java.lang.String.charAt(String.java:1544)
	at Main.last(Main.java:3)
	at Main.main(Main.java:7)
בעברית פשוטה: In plain words: StringIndexOutOfBoundsException: Index 4 out of bounds for length 4 בשורה 3: האות האחרונה היא באינדקס length() - 1.StringIndexOutOfBoundsException: Index 4 out of bounds for length 4 on line 3: the last letter is at index length() - 1.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

טעות נפוצהCommon mistake

מדף, צעד 11: שלושה באגים

Shelf, step 11: three bugs

Main.java
public class Main {
    public static void main(String[] args) {
        String[] titles = {"Dune", "Emma", "Ulysses"};
        int[] ratings = {5, 4, 4};
        int sum = 0;
        for (int i = 0; i <= ratings.length; i++) {
            sum += ratings[i];
        }
        System.out.println("Average: " + sum / ratings.length);
        String wanted = new String("Emma");
        for (String t : titles) {
            if (t == wanted) {
                System.out.println("Found " + t);
            }
        }
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at Main.main(Main.java:7)
בעברית פשוטה: In plain words: באג 1: Index 3 out of bounds for length 3 בשורה 7, כי i <= ratings.length. אחרי שתתקנו, תגלו את 2 (חילוק שלמים נותן 4) ואת 3 (== על מחרוזות, ולכן Emma לא נמצאת).Bug 1: Index 3 out of bounds for length 3 on line 7, because i <= ratings.length. Once fixed you'll find 2 (integer division gives 4) and 3 (== on strings, so Emma isn't found).
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

טעות נפוצהCommon mistake

הבאג לא איפה שהוא נשבר

The bug isn't where it breaks

Main.java
public class Main {
    static double parsePrice(String text) {
        return Double.parseDouble(text);
    }

    static double total(String[] prices) {
        double sum = 0;
        for (String p : prices) {
            sum += parsePrice(p);
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(total(new String[]{"10.5", "2,00"}));
    }
}
מה Java עונה (התוכנית קורסת)What Java says (the program crashes)
Exception in thread "main" java.lang.NumberFormatException: For input string: "2,00"
	at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
	at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
	at java.base/java.lang.Double.parseDouble(Double.java:792)
	at Main.parsePrice(Main.java:3)
	at Main.total(Main.java:9)
	at Main.main(Main.java:15)
בעברית פשוטה: In plain words: NumberFormatException: For input string: "2,00": ה-trace עובר דרך parsePrice (שורה 3), total (שורה 9) ו-main (שורה 15). parseDouble מכיר רק נקודה.NumberFormatException: For input string: "2,00": the trace goes through parsePrice (line 3), total (line 9) and main (line 15). parseDouble only knows a dot.
צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

06הצעד של היום בפרויקט מדףToday's step in the Shelf project

בקוד של המדף יש שלושה באגים. הראשון מפיל את התוכנית, ושני האחרים מסתתרים מאחוריו. תקנו אחד-אחד, והריצו אחרי כל תיקון. בסוף צריך להודפס Average: 4.333333333333333 ואז Found Emma.

The shelf code has three bugs. The first crashes the program, and the other two hide behind it. Fix them one at a time, running after each fix. In the end it should print Average: 4.333333333333333 then Found Emma.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

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