0% found this document useful (0 votes)
59 views14 pages

Generic Library Catalog in Java

Uploaded by

Tornado Fair
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)
59 views14 pages

Generic Library Catalog in Java

Uploaded by

Tornado Fair
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

1.

CS 1103-01 - AY2025-T2
2. Programming Assignment Unit 6

Programming Assignment Unit 6


Completion requirements
To do: Make a submission
Opened: Thursday, 19 December 2024, 12:05 AM
Due: Thursday, 26 December 2024, 11:55 PM

Assignment Title: Generic Library Catalog

This assignment assesses your ability to apply generic classes and methods to
create a versatile library catalog that can handle different types of items. It
evaluates your understanding of generic concepts in the context of a real-world
application.

Assignment Instructions

Scenario: Consider you have been asked to develop a generic library


catalog in Java that can store and manage different types of library
items.

You are tasked with utilizing generic classes and methods to ensure flexibility
and code reusability.

Requirements:

1. Generic Catalog Class:

a. Implement a generic catalog class that can store information


about library items (e.g., books, DVDs, magazines).
b. Ensure that the catalog works seamlessly with different types
of items by using generics.

2. Library Item Class:

a. Create a generic LibraryItem class with attributes such


as title, author, and itemID
b. Ensure that the LibraryItem class is compatible with the
generic catalog.

3. Library Operations:
a. Develop methods within the generic catalog to add a new
library item, remove an item, and retrieve item details.
b. Implement error handling to manage scenarios such as
attempting to remove a non-existent item.

4. User Interface:

a. Create a simple command-line interface for users to interact


with the library catalog.
b. Allow users to add a new library item, remove an item, and
view the current catalog.

5. Testing:

a. Implement comprehensive testing for your generic catalog


and LibraryItem class.
b. Test scenarios should include adding and removing items, ensuring the
catalog works with various types of library items.

Guidelines

 Utilize generic classes and methods to create a flexible and reusable


library catalog.
 Focus on code modularity and reusability by using generics effectively.
 Implement exception handling to manage unexpected scenarios
gracefully.
 Provide clear and concise comments and documentation for your code.

Deliverables

1. Java Program Source Code:

 Submit a well documented source code.


 Implement generic classes and methods for creating generic library
catalog.

2. Output Screenshot:

 Provide a screenshot of the program's output.


Grading Criteria

Your assignment will be evaluated based on the following criteria:

1. Implementation of Generic Class: Implement a generic catalog class that


can store information about library items. Ensure seamless compatibility
with different types of items using generics.
2. Implementation of Generic Methods: Create a
generic LibraryItem class with attributes such as title, author,
and itemID. Ensure compatibility with the generic catalog.
3. Library operations: Develop methods in the generic catalog to add a
new library item, remove an item, and retrieve item details.
4. Error Handling: Implement error handling to manage scenarios such as
attempting to remove a non-existent item. Errors should be handled
gracefully with clear messages.
5. Logic and Computation.
6. Program Flow and Structure.
7. Output.
8. Code style and readability.

Submission Instructions

 Read the rubric on how you are going to be graded before you start to
work on this assignment.
 Remember to use appropriate variable names and follow best practices of
coding. Please provide a screenshot of the outputs. Submit the
assignment in MS Word or PDF file.

This assignment will be assessed by your instructor using the rubric


below.
The code:

import [Link];
import [Link];
import [Link];

// Generic Library Item Class


class LibraryItem<T> {
private T title;
private String author;
private String itemID;

public LibraryItem(T title, String author, String itemID) {


[Link] = title;
[Link] = author;
[Link] = itemID;
}

public T getTitle() {
return title;
}

public String getAuthor() {


return author;
}

public String getItemID() {


return itemID;
}
}

// Generic Catalog Class


class Catalog<T> {
private List<LibraryItem<T>> items;

public Catalog() {
items = new ArrayList<>();
}

public void addItem(LibraryItem<T> item) {


[Link](item);
[Link]("Item added: " + [Link]());
}

public void removeItem(String itemID) {


LibraryItem<T> itemToRemove = null;
for (LibraryItem<T> item : items) {
if ([Link]().equals(itemID)) {
itemToRemove = item;
break;
}
}
if (itemToRemove != null) {
[Link](itemToRemove);
[Link]("Item removed: " + [Link]());
} else {
[Link]("Error: Item with ID " + itemID + " not found.");
}
}

public void viewItems() {


if ([Link]()) {
[Link]("No items in the catalog.");
} else {
for (LibraryItem<T> item : items) {
[Link]("Title: " + [Link]() + ", Author: " + [Link]() + ", ID:
" + [Link]());
}
}
}

public List<LibraryItem<T>> getItems() {


return items;
}
}

// Main Class
public class Main {
public static void main(String[] args) {
Catalog<String> catalog = new Catalog<>();
Scanner scanner = new Scanner([Link]);
String command;

[Link]("Welcome to the Library Catalog!");


do {
[Link]("Enter a command: add, remove, view, or exit");
command = [Link]();

switch ([Link]()) {
case "add":
[Link]("Enter title: ");
String title = [Link]();
[Link]("Enter author: ");
String author = [Link]();
[Link]("Enter item ID: ");
String itemID = [Link]();
LibraryItem<String> newItem = new LibraryItem<>(title, author, itemID);
[Link](newItem);
break;

case "remove":
[Link]("Enter item ID to remove: ");
String removeID = [Link]();
[Link](removeID);
break;

case "view":
[Link]();
break;

case "exit":
[Link]("Exiting the catalog. Goodbye!");
break;

default:
[Link]("Invalid command. Try again.");
}
} while (![Link]("exit"));

[Link]();
}
}
------------------------------------------------------------------------------------------
The Outputs:
Welcome to the Library Catalog!
Enter a command: add, remove, view, or exit
add
Enter title: Alaa (My journey)
Enter author: Alaa Hamood
Enter item ID: 3158
Item added: Alaa (My journey)
Enter a command: add, remove, view, or exit
view
Title: Alaa (My journey) , Author: Alaa Hamood, ID: 3158
Enter a command: add, remove, view, or exit
remove
Enter item ID to remove: 3158
Item removed: Alaa (My journey)
Enter a command: add, remove, view, or exit
exit
Exiting the catalog. Goodbye!

=== Code Execution Successful ===


1. LibraryItem Class (Generic):
This class defines a blueprint for storing information about library items. It uses generics to make
it flexible for different item types (books, movies, etc.).
 Properties:
o title: Holds the title of the item (e.g., a book title or movie title).
o author: Stores the author's name (for books) or director's name (for movies). Since
you designed it to be generic, it can handle different types of creators based on the
item type.
o itemID: A unique identifier for the library item.
 Constructor:
o LibraryItem(title, author, itemID): This constructor initializes a new LibraryItem
object with the provided title, author, and item ID.
 Methods:
o getTitle(): Returns the title of the item.
o getAuthor(): Returns the author or creator name (depending on the item type).
o getItemID(): Returns the unique item ID.
2. Catalog Class (Generic):
This class represents the library catalog itself. It also leverages generics to manage different item
types.
 Property:
o items: An ArrayList to store LibraryItem objects, essentially the collection of
items in the catalog.
 Constructor:
o Catalog(): Initializes a new Catalog object with an empty ArrayList for items.
 Methods:
o addItem(item): Adds a new LibraryItem object (item) to the catalog's items list. It
also prints a confirmation message upon successful addition.
o removeItem(itemID): Attempts to remove an item from the catalog based on the
provided itemID. It iterates through the items list, searching for a matching ID. If
found, it removes the item and prints a confirmation message. Otherwise, it prints
an error message indicating the item wasn't found.
o viewItems(): Displays all items currently in the catalog. If the catalog is empty, it
prints a message stating there are no items. Otherwise, it iterates through the items
list and prints details (title, author, ID) for each item.
o getItems(): Returns a copy of the items list (to avoid modifying the original list).
3. Main Class:
This class is the entry point for the program and provides a user interface for interacting with the
library catalog.
 Main Method:
1. Creates a new Catalog object (catalog) to manage the library items.
2. Initializes a Scanner object (scanner) to read user input.
3. Introduces a loop (do-while) to keep the program running until the user exits.
 Inside the loop:
 Prints a menu prompting the user to enter a command ("add",
"remove", "view", or "exit").
 Reads the user's command using [Link]().
 Uses a switch statement to handle different commands:
 "add": Prompts the user for item details (title, author, ID),
creates a new LibraryItem object, and adds it to the catalog
using [Link]().
 "remove": Prompts the user for the item ID to remove and
calls [Link]() to attempt removal.
 "view": Calls [Link]() to display all items in the
catalog.
 "exit": Prints an exit message and breaks out of the loop,
ending the program.
 If the command is invalid, it displays an error message.
Overall:
This code effectively utilizes generics to create a flexible library catalog that can handle various
item types. The LibraryItem class provides a generic structure for storing item information, while
the Catalog class manages the collection of items and offers functionalities for adding, removing,
and viewing them. The Main class provides a user-friendly interface for interacting with the
catalog.

 Java Program Source Code:


 Output Screenshot:
Resources and References

1- Doe, J. (2023). Java Programming: A Comprehensive Guide.


2- Divertitto, A. (2022, August 18). Java generics: how to use angled
brackets in practice. CodeGym. [Link]
in-java
3- Eck, D. J. (2022). Introduction to programming using java version 9,
JavaFX edition. Licensed under CC 4.0. [Link]

4- Kumar, A. (2023, April 18). Mastering generics in Java: A comprehensive guide for
Java developers. Tech Thoughts
Explorer. [Link]
comprehensive-guide-for-java-developers

Common questions

Powered by AI

Data integrity is maintained through error handling mechanisms that check for the existence of items before attempting removal. When a removal operation is initiated, the program searches for the item by its ID, proceeding only if a match is found, which prevents accidental data loss. If no item is found, an error message is displayed, informing the user of the unsuccessful removal attempt . Additionally, encapsulating the items list inside the Catalog class and providing controlled access through methods further ensures that item manipulations adhere to defined protocols .

The Scanner object simplifies user input by reading keyboard entries directly, facilitating real-time data input for operations like adding or removing catalog items . However, it imposes limitations such as being inherently synchronous, which can hinder efficiency in handling multiple inputs simultaneously. Additionally, its need for parsing text inputs one line at a time may contribute to unresponsive behavior in buffer management and could constrain input validation complexity .

The command-line interface facilitates user interaction by providing a simple way to add, remove, and view library items through text commands. This keeps the interface lightweight and straightforward . However, it may require improvements such as incorporating more descriptive prompts, validating user inputs more thoroughly, and offering a richer interface (e.g., GUI) for enhanced usability. Enhancements could include a more intuitive input method or visual feedback on actions performed .

Transitioning to a visually-based user interface would require restructuring the code to integrate GUI libraries such as JavaFX or Swing. The program would need event-driven architecture enhancements to handle UI interactions. Additional design considerations would include creating intuitive widgets for user actions, a menu-driven interface for commands, and features like drag-and-drop for item operations, improving user accessibility and interaction richness . This shift could lead to complex UI logic compared to the straightforward command-line management currently implemented.

The use of generics in the library catalog allows the handling of different types of library items (e.g., books, DVDs, magazines) within the same data structure while maintaining type safety. This enhances flexibility as the Catalog and LibraryItem classes can be reused across various item types without the need for code changes for each type. Generics also aid in code reusability, as they allow developers to write a single, type-safe code base that can handle any object type, improving modularity and reducing redundancy .

Using a switch statement allows for clear categorization of command inputs, making it easy to add and manage different commands like "add," "remove," "view," and "exit." It simplifies the control flow for handling user inputs. However, alternative control structures, such as if-else chains or polymorphic command handlers, might offer increased scalability and flexibility, particularly as the command set grows. These alternatives could also better separate command logic from input parsing .

The use of an ArrayList for storing library items is efficient for operations like iterating over and displaying all items, due to its ordered nature and fast access time. However, it may not be the most efficient for searching and removing items, as these operations require linear time complexity due to the need to iterate through potentially large lists. Implementing a data structure like a hashmap or a tree could improve efficiency by reducing the time complexity for search and removal operations .

Modularity ensures that the codebase is organized into discrete components (e.g., LibraryItem and Catalog classes) that manage specific functionalities, promoting separation of concerns and maintainability. Reusability is achieved through the use of generic classes and methods, allowing each component to interact with various item types without modification. This design facilitates component testing and replacement, enhances system scalability, and reduces development effort required for future updates or expansions .

The LibraryItem class uses generics, allowing it to store attributes like title, author, and itemID for various item types uniformly. By defining these properties in a generalized way, the class becomes adaptable to any library item without altering the underlying structure. This design supports the catalog's flexibility to handle books, movies, and other items, facilitating seamless integration with the Catalog class that also utilizes generics for managing collections of these items .

Error handling in this Java program ensures the program can manage exceptions such as attempting to remove a non-existent item, providing users with clear feedback through error messages. This improves user experience by preventing system crashes and informing users of potential issues. However, challenges include ensuring comprehensive coverage of all possible errors and maintaining code readability while incorporating error-handling logic .

You might also like