0% found this document useful (0 votes)
18 views3 pages

Java Product Management System

This Java program manages a product inventory system where users can add, display, update stock, purchase products, and calculate the total stock value. It utilizes a Product class to encapsulate product details and a main class to handle user interactions through a console menu. The program ensures safe input handling for integers and doubles to prevent errors during user input.

Uploaded by

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

Java Product Management System

This Java program manages a product inventory system where users can add, display, update stock, purchase products, and calculate the total stock value. It utilizes a Product class to encapsulate product details and a main class to handle user interactions through a console menu. The program ensures safe input handling for integers and doubles to prevent errors during user input.

Uploaded by

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

import [Link].

ArrayList;
import [Link];

class Product {
private int id;
private String name;
private int quantity;
private double price;

public Product(int id, String name, int quantity, double price) {


[Link] = id;
[Link] = name;
[Link] = quantity;
[Link] = price;
}

public int getId() { return id; }


public String getName() { return name; }
public int getQuantity() { return quantity; }
public double getPrice() { return price; }

public void setQuantity(int quantity) { [Link] = quantity; }


public void setPrice(double price) { [Link] = price; }

@Override
public String toString() {
return "ID: " + id + " | Name: " + name + " | Quantity: " + quantity + " | Price: ₹" + price;
}
}

public class Main {


private static final ArrayList products = new ArrayList<>();
private static final Scanner sc = new Scanner([Link]);

private static int safeIntInput() {


while (![Link]()) {
[Link]("Invalid input. Enter an integer: ");
[Link]();
}
return [Link]();
}

private static double safeDoubleInput() {


while (![Link]()) {
[Link]("Invalid input. Enter a number: ");
[Link]();
}
return [Link]();
}

private static void addProduct() {


[Link]("Enter Product ID: ");
int id = safeIntInput();
[Link](); // consume newline
[Link]("Enter Product Name: ");
String name = [Link]();
[Link]("Enter Quantity: ");
int qty = safeIntInput();
[Link]("Enter Price: ");
double price = safeDoubleInput();

[Link](new Product(id, name, qty, price));


[Link]("Product added.\n");
}

private static void displayProducts() {


if ([Link]()) {
[Link]("No products.\n");
return;
}
[Link]("--- Products ---");
for (Product p : products) [Link](p);
[Link]();
}

private static void updateStock() {


[Link]("Enter Product ID to update: ");
int id = safeIntInput();
for (Product p : products) {
if ([Link]() == id) {
[Link]("Enter new quantity: ");
[Link](safeIntInput());
[Link]("Stock updated.\n");
return;
}
}
[Link]("Product not found.\n");
}

private static void processPurchase() {


[Link]("Enter Product ID to purchase: ");
int id = safeIntInput();
[Link]("Enter quantity to purchase: ");
int q = safeIntInput();
for (Product p : products) {
if ([Link]() == id) {
if ([Link]() >= q) {
[Link]([Link]() - q);
[Link]("Purchase successful. Total: ₹" + (q * [Link]()) + "\n");
} else {
[Link]("Not enough stock.\n");
}
return;
}
}
[Link]("Product not found.\n");
}
private static void calcValue() {
double total = 0;
for (Product p : products) total += [Link]() * [Link]();
[Link]("Current stock value: ₹" + total + "\n");
}

public static void main(String[] args) {


int choice;
do {
[Link]("[Link] [Link] [Link] [Link] [Link] [Link]");
[Link]("Choice: ");
choice = safeIntInput();
switch (choice) {
case 1: addProduct(); break;
case 2: displayProducts(); break;
case 3: updateStock(); break;
case 4: processPurchase(); break;
case 5: calcValue(); break;
case 6: [Link]("Exiting."); break;
default: [Link]("Invalid choice.\n");
}
} while (choice != 6);
}
}

Common questions

Powered by AI

The `calcValue` method could be improved by providing aggregated insights such as the highest valued inventory item, the average price of products, or different views like value broken down by category (if such an attribute existed). Including functionality to record and present historical value changes over time could also provide trends in stock value, aiding in better financial planning and decision-making. Adding currency formatting and localization could enhance the method's utility across different markets .

The `Product` class encapsulates the attributes of a product by using private fields (id, name, quantity, price) and providing public getter and setter methods to access and modify these fields. This encapsulation is crucial in object-oriented programming as it restricts direct access to the class's fields, allowing only controlled manipulation via methods. This helps maintain the integrity of the data and prevents unintended interference from external code, supporting code reliability and maintainability .

Scalability concerns arise from the system's reliance on an `ArrayList` for storing products, as performance could degrade with very large numbers of items due to linear search operations. Additionally, all data is kept in memory, which is not scalable for massive datasets. To address these concerns, using a database for persistent storage could offload memory usage and enable more efficient operations (such as indexing). Adopting a more distributed architecture, like microservices, could also enhance scalability by segmenting functionalities into smaller, independently deployable units .

The `processPurchase` method manages inventory by deducting the purchased quantity from the product's available stock. It ensures transaction integrity by first checking if the requested quantity is available (i.e., current quantity is greater than or equal to the purchase quantity). If sufficient stock exists, it reduces the quantity and calculates the total price. If not, it informs the user of insufficient stock. This check ensures that stock levels are correctly managed and prevents overdrawing inventory resources .

The `Main` class ensures input validity by implementing the methods `safeIntInput` and `safeDoubleInput`. These methods use a `while` loop to check if the input from the `Scanner` object is of the expected type (integer or double, respectively). If not, they prompt the user for valid input until a correct type is entered. This process prevents exceptions that would occur from invalid input types and ensures that only valid data is processed by the program .

Using a `switch` statement for menu navigation consolidates decision logic and is straightforward for controlling program flow based on user input, covering all expected cases. However, it can be less flexible and readable with many options, especially when menu items change frequently. An alternative approach like using an `enum` with method references could improve readability and maintainability by separating the choice logic from actual methods and allowing easier extension or modification of menu options without altering the control flow structure substantially .

When a non-existent product is referenced, the code handles it by iterating through the `ArrayList` of products and printing 'Product not found' if no match is found. While this provides immediate feedback, it lacks robustness as it does not specify potential next steps or error details. Limitations include the user being unaware of remedial actions like adding the missing product, and the system not logging such incidents for further analysis. Enhancing user experience by suggesting corrective actions or automatically proceeding to add a new product could address these limitations .

The `Product` class exemplifies encapsulation by keeping attributes private and exposing public methods for access. Its design focuses on representing a single product entity, embodying the principle of abstraction by modeling real-world items. The `Main` class, albeit less object-oriented with its procedural approach, demonstrates the use of encapsulation and modular design by organizing functionalities (e.g., adding products, updating stock) into self-contained static methods. Together, they illustrate principles of encapsulation, modularity, and abstraction in object-oriented design .

Using a static `ArrayList` in the `Main` class to store products allows easy access and manipulation of the product list across the static methods of the class. The benefits include centralized management of products, ease of implementing list-based operations, and no need for object instantiation to handle products. However, drawbacks include potential memory issues as the list persists throughout the application's lifetime, limiting scalability with large datasets. Additionally, all static methods have access to this `ArrayList`, which can lead to unintended modifications if not managed carefully .

The `Main` class updates product stock using the `updateStock` method, which prompts the user for a product ID and new quantity. It iterates through the products list to find a matching ID and updates the quantity using the `setQuantity` method of the `Product` class. Edge cases not addressed include handling non-existent product IDs beyond printing a simple 'Product not found' message, negative quantities (as no validation is enforced), and no confirmation before changing stock, which may lead to accidental updates .

You might also like