0% found this document useful (0 votes)
19 views5 pages

Java Library System with HashMap

The document describes a Java program that simulates a library system, allowing users to manage book inventory through a menu-driven interface. It features a LibrarySystem class with methods for adding, borrowing, and returning books, utilizing a HashMap for efficient data storage. Basic error handling is included to ensure user-friendly interaction with the system.

Uploaded by

falakfraidoon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views5 pages

Java Library System with HashMap

The document describes a Java program that simulates a library system, allowing users to manage book inventory through a menu-driven interface. It features a LibrarySystem class with methods for adding, borrowing, and returning books, utilizing a HashMap for efficient data storage. Basic error handling is included to ensure user-friendly interaction with the system.

Uploaded by

falakfraidoon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programming Assignment Unit 2

The Java program simulates a straightforward library system where users can manage book
inventory through various operations. Central to the program is the LibrarySystem class, which
includes a nested Book class to encapsulate details such as title, author, and quantity for each
book. Utilizing a HashMap named library, the program efficiently stores and retrieves book
information based on the book title.

When the application runs, users are greeted with a menu-driven interface with choices to add
books, borrow books, return books, and log out of the system. A distinct method in the
LibrarySystem class is associated with each menu option: addBooks, borrowBooks, and
returnBooks.

Users can update the quantity of an existing book or input details about a new one using the
addBooks method. It verifies if the book already exists in the library; if so, it changes the
amount; otherwise, it adds the book as a new entry.

When borrowing books, users are prompted by the borrowBooks method to indicate the title of
the book and the quantity of copies they want to check out. It checks the library to see if the
requested quantity is available before updating the quantity to account for the books that have
been borrowed. Conversely, the returnBooks method handles the return process, requiring users
to submit the book title and the quantity of copies they are returning. It modifies the number of
books that have been returned to the library.

Basic error handling is built into the application to handle situations like trying to borrow more
books than are available or entering erroneous information. With its concise instructions and
educational information, it guarantees that users can engage with the system without difficulty.
To exit the software, simply choose the relevant menu item and make sure that all resources have
been closed correctly.

Here is the source code:


import [Link];
import [Link];

public class Main {

// Book class to store details of each book


static class Book {
String title;
String author;
int quantity;

Book(String title, String author, int quantity) {


[Link] = title;
[Link] = author;
[Link] = quantity;
}
}
// HashMap to store books with title as the key
static HashMap<String, Book> library = new HashMap<>();

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
int choice;

while (true) {
// Display menu options
[Link]("\nLibrary System Menu:");
[Link]("1. Add Books");
[Link]("2. Borrow Books");
[Link]("3. Return Books");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link](); // Consume newline

switch (choice) {
case 1:
addBooks(scanner);
break;
case 2:
borrowBooks(scanner);
break;
case 3:
returnBooks(scanner);
break;
case 4:
[Link]("Exiting the system. Goodbye!");
[Link]();
[Link](0);
default:
[Link]("Invalid choice! Please try again.");
}
}
}

// Method to add books to the library


public static void addBooks(Scanner scanner) {
[Link]("Enter book title: ");
String title = [Link]();
[Link]("Enter author name: ");
String author = [Link]();
[Link]("Enter quantity: ");
int quantity = [Link]();
[Link](); // Consume newline

if ([Link](title)) {
Book existingBook = [Link](title);
[Link] += quantity;
[Link]("Book already exists. Updated the quantity.");
} else {
[Link](title, new Book(title, author, quantity));
[Link]("New book added to the library.");
}
}

// Method to borrow books from the library


public static void borrowBooks(Scanner scanner) {
[Link]("Enter book title: ");
String title = [Link]();
[Link]("Enter quantity to borrow: ");
int quantity = [Link]();
[Link](); // Consume newline

if ([Link](title)) {
Book book = [Link](title);
if ([Link] >= quantity) {
[Link] -= quantity;
[Link]("You have successfully borrowed " +
quantity + " copy/copies of \"" + title + "\".");
} else {
[Link]("Not enough copies available. Available
quantity: " + [Link]);
}
} else {
[Link]("Book not found in the library.");
}
}

// Method to return books to the library


public static void returnBooks(Scanner scanner) {
[Link]("Enter book title: ");
String title = [Link]();
[Link]("Enter quantity to return: ");
int quantity = [Link]();
[Link](); // Consume newline

if ([Link](title)) {
Book book = [Link](title);
[Link] += quantity;
[Link]("You have successfully returned " + quantity +
" copy/copies of \"" + title + "\".");
} else {
[Link]("Book not recognized by the library.");
}
}
}

Output screenshot:
The screenshots of code running on IDE:

References:
Eck, D. J. (2022). Introduction to programming using Java: Version 9, Swing
edition. Hobart and William Smith Colleges.
W3Schools. (n.d.). Java tutorial. W3Schools. [Link]

Common questions

Powered by AI

The nested Book class is crucial for encapsulating and organizing book-related data within the library system. By storing details such as title, author, and quantity, it provides a structured way to manage this information, allowing for efficient data retrieval and modification. The class enhances code readability and maintainability by localizing book-specific logic, reducing complexity in the main program structure, and simplifying operations on book data .

When adding new books, the "addBooks" method first checks if the book title already exists in the HashMap with library.containsKey(title). If it exists, it updates the quantity of the existing entry. Otherwise, it adds the book as a new entry. Basic error handling includes checking for existing titles and updating accordingly, which prevents duplicate entries. While the basic input is managed, further input validation (e.g., non-negative quantities) could enhance robustness .

To enhance scalability, consider implementing a database to store and manage book inventories instead of a HashMap. A database can handle larger amounts of data and provides robust querying capabilities, transactions, and persistent storage. This transition would require adding a data access layer to interact with the database and updating method logic (addBooks, borrowBooks, returnBooks) to use SQL queries. Such improvements can significantly increase the system's capacity and reliability .

The menu-driven interface in the Java library system enhances usability by providing a clear, structured set of options that guide the user through the system's available operations. It offers concise instructions, ensuring users can easily understand and navigate tasks such as adding, borrowing, and returning books. Error handling is also incorporated to provide feedback for invalid selections, thus preventing user confusion and facilitating a smooth interaction .

To handle cases where users attempt to borrow a non-existent book title, the program already checks if the title exists in the library using library.containsKey(title). If the check fails, it outputs "Book not found in the library." To improve this, the prompt could suggest checking the spelling of the title or offer a list of available titles. Additionally, it could introduce a feature where users can request the desired books to be added to the library, thus enhancing the user experience .

The exit procedure in the Java program is handled by selecting the 'Exit' option from the menu, represented by choice '4'. Upon user selection, the program outputs a farewell message, closes the Scanner object with scanner.close(), and calls System.exit(0) to terminate the program. This ensures that all resources, such as I/O streams, are correctly closed, preventing memory leaks or resource locking, thus ensuring proper system shutdown .

The Java library system uses the "borrowBooks" method to ensure users do not borrow more copies than available. When a user attempts to borrow a book, the method first checks if the book title exists in the HashMap. If the book exists, it then compares the requested quantity with the available quantity (book.quantity). If the available quantity is not sufficient, the system informs the user by displaying the available quantity. This validation prevents over-borrowing .

Closing the Scanner is crucial as it releases the underlying I/O resources associated with the stream, preventing potential resource leaks. If omitted, it could lead to memory leaks and, in some environments, locked resources, which degrade system performance over time. The orderly termination using scanner.close() ensures efficient memory management, vital for applications with longer runtimes or those running in resource-constrained environments .

Enhancing error messages can greatly improve user experience. Current messages like "Invalid choice!" or "Book not recognized" are informative but could be expanded by offering guidance for corrective action, such as "Please enter a valid menu option (1-4)" or "Book not recognized. Consider checking the title spelling or adding new entries if necessary." Including suggestions or further steps makes the system more user-friendly and provides a more intuitive interaction .

Using a HashMap to store books offers benefits such as fast lookup and retrieval times, which is crucial for operations like checking book availability. HashMaps allow a book's title to be used as a unique key, ensuring constant time complexity, O(1), for search operations. However, a potential drawback is that HashMaps require more memory due to hashing overheads, and they do not maintain any order of entries. Additionally, there is an implicit risk of collision, although it's mitigated in practice by a good hashing function .

You might also like