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

JavaJava
6
חלקPart 1: יסודותFoundations כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Scanner וקלטScanner & input

קריאת קלט עם Scanner, nextLine מול nextInt והמלכודת שביניהם, בדיקת קלט ותפריט טקסט ראשון.

Reading input with Scanner, nextLine vs nextInt and the trap between them, validating input and a first text menu.

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

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

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

  • קלט: מה שהמשתמש מקליד לתוכנית בזמן שהיא רצה. בבדיקות כאן, הקלט מוקלד מראש.input: What the user types into the program while it runs. In the checks here, the input is typed in advance.
  • Scanner: מחלקה שקוראת קלט: Scanner sc = new Scanner(System.in);, ואז sc.nextLine(), sc.nextInt() וכו'.Scanner: A class that reads input: Scanner sc = new Scanner(System.in);, then sc.nextLine(), sc.nextInt() and so on.
  • מילה (token): חתיכת קלט בין רווחים או שורות. nextInt ו-next קוראים מילה אחת, ו-nextLine קורא שורה שלמה.token: A piece of input between spaces or lines. nextInt and next read one token; nextLine reads a whole line.
  • מלכודת nextInt: nextInt קורא את המספר אבל משאיר את ה-Enter. ה-nextLine הבא קורא את השארית הריקה. הפתרון: nextLine() נוסף אחרי nextInt.the nextInt trap: nextInt reads the number but leaves the Enter behind. The next nextLine reads that empty leftover. The fix: an extra nextLine() after nextInt.
  • בדיקת קלט: בודקים שהקלט הגיוני לפני שמשתמשים בו: hasNextInt() לפני nextInt(), ובדיקת טווח.input validation: Checking input makes sense before using it: hasNextInt() before nextInt(), and a range check.
  • import: שורה בראש הקובץ שמביאה מחלקה מספרייה: import java.util.Scanner;.import: A line at the top of the file that brings in a library class: import java.util.Scanner;.

02קריאת שורה ומספרReading a line and a number

מייבאים את Scanner, יוצרים אחד על System.in, וקוראים. התוכנית מחכה עד שמקלידים ולוחצים Enter. כאן הקלט הוקלד מראש (מודגש בפלט).

Import Scanner, create one on System.in, and read. The program waits until you type and press Enter. Here the input was typed in advance (shown in the output).

Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.print("Age: ");
        int age = sc.nextInt();
        System.out.println(name + " will be " + (age + 1) + " next year");
    }
}
פלטOutput
Name: Dana
Age: 30
Dana will be 31 next year
צפו בהרצה צעד אחר צעד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

03המלכודת של nextIntThe nextInt trap

nextInt קורא רק את המספר ומשאיר את ה-Enter בצד. ה-nextLine שאחריו מקבל שורה ריקה! מוסיפים sc.nextLine(); אחרי nextInt כדי "לבלוע" את ה-Enter.

nextInt reads only the number and leaves the Enter behind. The nextLine after it gets an empty line! Add sc.nextLine(); after nextInt to "swallow" the Enter.

Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        sc.nextLine();
        String city = sc.nextLine();
        System.out.println(age + " from " + city);
    }
}
פלטOutput
30
Haifa
30 from Haifa
צפו בהרצה צעד אחר צעד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בודקים לפני שקוראיםCheck before reading

hasNextInt() שואל אם המילה הבאה היא מספר, בלי לקרוא אותה. אם לא, קוראים אותה עם next() וזורקים. ככה התוכנית לא קורסת על abc.

hasNextInt() asks whether the next token is a number without reading it. If not, read it with next() and drop it. That way the program doesn't crash on abc.

Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (!sc.hasNextInt()) {
            String bad = sc.next();
            System.out.println(bad + " is not a number");
        }
        int n = sc.nextInt();
        System.out.println("Got " + n);
    }
}
פלטOutput
abc
abc is not a number
xyz
xyz is not a number
42
Got 42
צפו בהרצה צעד אחר צעד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תפריט שחוזרA menu that repeats

לולאה שקוראת פקודה, switch שמחליט מה לעשות, ומשתנה שאומר מתי לצאת.

A loop that reads a command, a switch that decides what to do, and a variable that says when to quit.

Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean running = true;
        while (running) {
            String cmd = sc.nextLine();
            switch (cmd) {
                case "hi" -> System.out.println("Hello!");
                case "quit" -> running = false;
                default -> System.out.println("Unknown: " + cmd);
            }
        }
        System.out.println("Bye");
    }
}
פלטOutput
hi
Hello!
help
Unknown: help
quit
Bye
צפו בהרצה צעד אחר צעד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

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

תפריט שקורא שורות: add <title> מוסיף ספר, list מדפיס Books (2): Dune, Emma, quit יוצא ומדפיס Bye. שמרו את הרשימה ב-StringBuilder ומונה. (בבדיקה: add Dune, add Emma, list, quit.)

A menu reading lines: add <title> adds a book, list prints Books (2): Dune, Emma, quit leaves and prints Bye. Keep the list in a StringBuilder and a counter. (The check: add Dune, add Emma, list, quit.)

טיפ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