ASSIGNMENT-2 IMPLEMENTING A BASIC LIBRARY SYSTEM IN JAVA
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LibrarySystem {
private Map<String, Integer> books = new HashMap<>();
private Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
LibrarySystem librarySystem = new LibrarySystem();
librarySystem.runLibrarySystem();
}
public void runLibrarySystem() {
boolean exit = false;
while (!exit) {
System.out.println("Options:");
System.out.println("1. Add Books");
System.out.println("2. Borrow Books");
System.out.println("3. Return Books");
System.out.println("4. Exit");
int option = scanner.nextInt();
scanner.nextLine(); // Consume newline character
switch (option) {
case 1:
addBooks();
break;
case 2:
borrowBooks();
break;
case 3:
returnBooks();
break;
case 4:
exit = true;
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
scanner.close();
}
public void addBooks() {
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter author: ");
String author = scanner.nextLine();
System.out.print("Enter quantity: ");
int quantity = scanner.nextInt();
scanner.nextLine(); // Consume newline character
if (books.containsKey(title)) {
books.put(title, books.get(title) + quantity);
} else {
books.put(title, quantity);
}
}
public void borrowBooks() {
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter number of books to borrow: ");
int quantityToBorrow = scanner.nextInt();
scanner.nextLine(); // Consume newline character
if (books.containsKey(title)) {
int availableQuantity = books.get(title);
if (availableQuantity >= quantityToBorrow) {
books.put(title, availableQuantity - quantityToBorrow);
System.out.println("Books successfully borrowed.");
} else {
System.out.println("Requested quantity not available in the library.");
}
} else {
System.out.println("Book not found in the library.");
}
}
public void returnBooks() {
System.out.print("Enter book title: ");
String title = scanner.nextLine();
System.out.print("Enter number of books to return: ");
int quantityToReturn = scanner.nextInt();
scanner.nextLine(); // Consume newline character
if (books.containsKey(title)) {
int existingQuantity = books.get(title);
books.put(title, existingQuantity + quantityToReturn);
System.out.println("Books successfully returned.");
} else {
System.out.println("Cannot return books that do not belong to the library.");
}
}
}