מבחן 7: Java בעולם האמיתיExam 7: Java in the real world
אלגוריתמים, HTTP, מסדי נתונים ושכבות של שרת
Algorithms, HTTP, databases and server layers
90 דקותminutes4 שאלות בחירהmultiple choice3 שאלות קודcoding questions100 נקודותpoints
90:00השעון רק עוזר להתאמן. אפשר גם בלי.The timer is just for practice. You can skip it.
חלק א: שאלות בחירה (5 נקודות לשאלה)Part A: multiple choice (5 points each)
התשובות מתגלות רק כשמסיימים את המבחן.Answers are revealed only when you finish the exam.
חלק ב: שאלות קודPart B: coding questions
שאלהQuestion 5
חיפוש בינאריBinary search
כתבו static int binarySearch(int[] a, int target) בלולאה (בלי Arrays.binarySearch): מחזירה את האינדקס של target במערך ממוין, או -1. main מדפיס 3 -1.
Write static int binarySearch(int[] a, int target) with a loop (no Arrays.binarySearch): it returns target's index in a sorted array, or -1. main prints 3 -1.
איך הפלט אמור להיראות?What should the output look like?
3 -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:int mid = (lo + hi) >>> 1;int mid = (lo + hi) >>> 1;
רמזHint 2:while (lo <= hi).while (lo <= hi).
הפתרון שלנוOur solution
Main.java
publicclass Main {
staticint binarySearch(int[] a, int target) {
int lo =0;
int hi = a.length-1;
while (lo <= hi) {
int mid = (lo + hi) >>>1;
if (a[mid] == target) {
return mid;
}
if (a[mid] < target) {
lo = mid +1;
} else {
hi = mid -1;
}
}
return-1;
}
publicstaticvoidmain(String[] args) {
int[] a = {2, 5, 8, 12, 16, 23};
System.out.println(binarySearch(a, 12) +" "+ binarySearch(a, 7));
}
}
פלטOutput
3 -1
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מחווןRubric (25 נקודותpoints)
כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.
שאלהQuestion 6
נתבA router
כתבו static String handle(String method, String path): GET /books → 200 list; GET /books/7 (מספר) → 200 book 7; POST /books → 201 created; כתובת מוכרת עם method אחר → 405 method not allowed; כל השאר (גם /books/abc) → 404 not found.
Write static String handle(String method, String path): GET /books → 200 list; GET /books/7 (a number) → 200 book 7; POST /books → 201 created; a known address with another method → 405 method not allowed; everything else (/books/abc too) → 404 not found.
איך הפלט אמור להיראות?What should the output look like?
200 book 7
405 method not allowed
404 not found
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:קודם מזהים את הכתובת, אחר כך בודקים את ה-method.First recognize the address, then check the method.
publicclass Main {
staticString handle(String method, String path) {
if (path.equals("/books")) {
returnswitch (method) {
case"GET"->"200 list";
case"POST"->"201 created";
default->"405 method not allowed";
};
}
if (path.matches("/books/\\d+")) {
if (!method.equals("GET")) {
return"405 method not allowed";
}
return"200 book "+ path.substring("/books/".length());
}
return"404 not found";
}
publicstaticvoidmain(String[] args) {
System.out.println(handle("GET", "/books/7"));
System.out.println(handle("DELETE", "/books"));
System.out.println(handle("GET", "/authors"));
}
}
פלטOutput
200 book 7
405 method not allowed
404 not found
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מחווןRubric (25 נקודותpoints)
כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.
שאלהQuestion 7
שכבותLayers
בונים שרת ספרים בלי מסד נתונים אמיתי: record Book(int id, String title); ממשק BookRepo עם save, findById (מחזיר Optional<Book>) ו-all(); מחלקה MemoryRepo שמממשת אותו עם TreeMap; ו-BookService שמקבל BookRepo בבנאי. add(title) נותן מזהה רץ מ-1 וזורק IllegalArgumentException על כותרת ריקה; titleOf(id) מחזיר את הכותרת או "unknown". main מדפיס 1 2 Emma unknown 2.
Build a book server without a real database: record Book(int id, String title); a BookRepo interface with save, findById (returning Optional<Book>) and all(); a MemoryRepo class implementing it with a TreeMap; and a BookService that takes a BookRepo in its constructor. add(title) gives a running id from 1 and throws IllegalArgumentException on a blank title; titleOf(id) returns the title or "unknown". main prints 1 2 Emma unknown 2.
איך הפלט אמור להיראות?What should the output look like?
1 2 Emma unknown 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:ה-service לא יודע איך שומרים: הוא מדבר רק עם הממשק.The service doesn't know how things are stored: it only talks to the interface.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
publicclass Main {
publicstaticvoidmain(String[] args) {
BookService service =new BookService(new MemoryRepo());
int a = service.add("Dune");
int b = service.add("Emma");
try {
service.add(" ");
} catch (IllegalArgumentException e) {
// a blank title is rejected
}
System.out.println(a +" "+ b +" "+ service.titleOf(2) +" "+ service.titleOf(9) +" "+ service.count());
}
}
record Book(int id, String title) {
}
interface BookRepo {
void save(Book book);
Optional<Book> findById(int id);
List<Book> all();
}
class MemoryRepo implements BookRepo {
privatefinalMap<Integer, Book> books =newTreeMap<>();
publicvoid save(Book book) {
books.put(book.id(), book);
}
publicOptional<Book> findById(int id) {
returnOptional.ofNullable(books.get(id));
}
publicList<Book> all() {
returnnewArrayList<>(books.values());
}
}
class BookService {
privatefinal BookRepo repo;
privateint nextId =1;
BookService(BookRepo repo) {
this.repo = repo;
}
int add(String title) {
if (title ==null|| title.isBlank()) {
thrownewIllegalArgumentException("title is required");
}
int id = nextId++;
repo.save(new Book(id, title.trim()));
return id;
}
String titleOf(int id) {
return repo.findById(id).map(Book::title).orElse("unknown");
}
int count() {
return repo.all().size();
}
}
פלטOutput
1 2 Emma unknown 2
יש יותר מדרך נכונה אחת. אם הבדיקות עוברות, גם הפתרון שלכם נכון.There is more than one right way. If the checks pass, your solution is right too.
מחווןRubric (30 נקודותpoints)
כשכל הבדיקות עוברות, כל השורות מסומנות. אם לא, סמנו בעצמכם מה כן עשיתם נכון.When every check passes, all rows are ticked. If not, tick what you did get right.