Project: Library Manager
Completed
Build a small library system. Use a Book class (title, available yes/no) and a HashMap<String, Book>. Read n commands:
add <title>– add a book (printAdded <title>, orAlready have <title>)borrow <title>– printBorrowed <title>,<title> is out, orNo such bookreturn <title>– printReturned <title>(if it was out), otherwiseNot borrowed(also when the book doesn't exist)
At the end print Available: followed by the available titles in alphabetical order, separated by commas and spaces (or none).
Input
First n, then n commands. Titles are single words.
Output
One line per command, then the Available line.
Example
Input
7 add Dune add Emma borrow Dune borrow Dune return Emma add Dune borrow Ulysses
Output
Added Dune Added Emma Borrowed Dune Dune is out Not borrowed Already have Dune No such book Available: Emma
Editor
Java
Hints
books.get(title) returns null when the book isn't in the map.
A TreeSet sorts the available titles for you.
String.join(", ", set) joins them.
Solution explanation
The map finds a book by title instantly, and each Book object remembers whether it's out.
Show solution
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeSet;
class Book {
String title;
boolean available = true;
Book(String title) {
this.title = title;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
HashMap<String, Book> books = new HashMap<>();
for (int i = 0; i < n; i++) {
String cmd = sc.next();
String title = sc.next();
Book b = books.get(title);
if (cmd.equals("add")) {
if (b != null) {
System.out.println("Already have " + title);
} else {
books.put(title, new Book(title));
System.out.println("Added " + title);
}
} else if (cmd.equals("borrow")) {
if (b == null) {
System.out.println("No such book");
} else if (!b.available) {
System.out.println(title + " is out");
} else {
b.available = false;
System.out.println("Borrowed " + title);
}
} else {
if (b == null || b.available) {
System.out.println("Not borrowed");
} else {
b.available = true;
System.out.println("Returned " + title);
}
}
}
TreeSet<String> free = new TreeSet<>();
for (Book b : books.values()) {
if (b.available) free.add(b.title);
}
System.out.println("Available: " + (free.isEmpty() ? "none" : String.join(", ", free)));
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module