Library System
Completed
Build a library with commands: add ID TITLE, borrow ID USER, return ID, status. Borrowing an unknown or already-borrowed book prints an error. status prints every book sorted by id as ID TITLE available or ID TITLE borrowed by USER.
Input
n, then n commands (titles are single words).
Output
Errors and status reports.
Example
Input
8 add B2 Dune add B1 Emma borrow B1 ann borrow B1 bob borrow B9 cy status return B1 status
Output
error: B1 already borrowed error: no book B9 B1 Emma borrowed by ann B2 Dune available B1 Emma available B2 Dune available
Editor
Java
Hints
Keep books in a TreeMap so status is sorted by id.
A null borrower means available.
Solution explanation
Model the domain with a small class, keep objects in a map, and handle each command in its own branch.
Show solution
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
class Book {
final String id, title;
String borrower;
Book(String id, String title) {
this.id = id;
this.title = title;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String, Book> books = new TreeMap<>();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String cmd = sc.next();
if (cmd.equals("add")) {
String id = sc.next();
books.put(id, new Book(id, sc.next()));
} else if (cmd.equals("borrow")) {
String id = sc.next(), user = sc.next();
Book b = books.get(id);
if (b == null) System.out.println("error: no book " + id);
else if (b.borrower != null) System.out.println("error: " + id + " already borrowed");
else b.borrower = user;
} else if (cmd.equals("return")) {
Book b = books.get(sc.next());
if (b != null) b.borrower = null;
} else {
for (Book b : books.values()) {
System.out.println(b.id + " " + b.title + (b.borrower == null ? " available" : " borrowed by " + b.borrower));
}
}
}
}
}