Smart E-commerce Cart Java, API

👤 Sharing: AI
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Represents a Product
class Product {
    private String id;
    private String name;
    private double price;
    private String category; // Add a category

    public Product(String id, String name, double price, String category) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.category = category;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public String getCategory() { return category; }

    @Override
    public String toString() {
        return "Product{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", category='" + category + '\'' +
                '}';
    }
}

// Represents the Shopping Cart
class ShoppingCart {
    private Map<String, Integer> items; // <ProductId, Quantity>
    private List<Product> availableProducts; // List of products to choose from.

    public ShoppingCart(List<Product> availableProducts) {
        this.items = new HashMap<>();
        this.availableProducts = availableProducts;
    }

    // Add a product to the cart
    public void addItem(String productId, int quantity) {
        // Validate if the product exists
        Product product = findProduct(productId);
        if (product == null) {
            System.out.println("Product with ID " + productId + " not found.");
            return;
        }


        items.put(productId, items.getOrDefault(productId, 0) + quantity);
        System.out.println(quantity + " " + product.getName() + "(s) added to cart.");

    }

    // Remove a product from the cart
    public void removeItem(String productId, int quantity) {
        if (!items.containsKey(productId)) {
            System.out.println("Product with ID " + productId + " not in cart.");
            return;
        }

        int currentQuantity = items.get(productId);
        if (quantity >= currentQuantity) {
            items.remove(productId);
            System.out.println("All " + findProduct(productId).getName() + "(s) removed from cart.");
        } else {
            items.put(productId, currentQuantity - quantity);
            System.out.println(quantity + " " + findProduct(productId).getName() + "(s) removed from cart.");
        }
    }

    // Get the total price of the cart
    public double getTotalPrice() {
        double total = 0;
        for (Map.Entry<String, Integer> entry : items.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            Product product = findProduct(productId); //Find the product from the available products.
            if (product != null) { // Null check to prevent errors.
                total += product.getPrice() * quantity;
            }

        }
        return total;
    }

    //Display the cart contents.
    public void displayCart() {
        if (items.isEmpty()) {
            System.out.println("Cart is empty.");
            return;
        }

        System.out.println("--- Cart Contents ---");
        for (Map.Entry<String, Integer> entry : items.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            Product product = findProduct(productId);

            if (product != null) { //Null check here too
                System.out.println(product.getName() + " (Quantity: " + quantity + ") - $" + product.getPrice() * quantity);
            }
        }
        System.out.println("----------------------");
        System.out.println("Total: $" + getTotalPrice());
    }


    //Helper method to find a product by ID.
    private Product findProduct(String productId) {
        for (Product product : availableProducts) {
            if (product.getId().equals(productId)) {
                return product;
            }
        }
        return null;
    }
}


// Mock API class (simulates fetching data from an external source)
class ProductAPI {

    //Simulates fetching products from a database or external API
    public static List<Product> getAllProducts() {
        List<Product> products = new ArrayList<>();
        products.add(new Product("101", "Laptop", 1200.00, "Electronics"));
        products.add(new Product("102", "Mouse", 25.00, "Electronics"));
        products.add(new Product("103", "Keyboard", 75.00, "Electronics"));
        products.add(new Product("104", "T-Shirt", 20.00, "Apparel"));
        products.add(new Product("105", "Jeans", 60.00, "Apparel"));

        return products;
    }

    //Simulates fetching product by ID
    public static Product getProductById(String productId) {
        List<Product> products = getAllProducts();
        for (Product product : products) {
            if (product.getId().equals(productId)) {
                return product;
            }
        }
        return null;
    }

}


// Main application class
public class SmartECommerceCart {

    public static void main(String[] args) {
        // Simulate fetching products from the API
        List<Product> products = ProductAPI.getAllProducts();

        // Create a shopping cart instance, passing the available products
        ShoppingCart cart = new ShoppingCart(products);

        // Add items to the cart
        cart.addItem("101", 1); // Laptop x 1
        cart.addItem("102", 2); // Mouse x 2
        cart.addItem("104", 3); // T-Shirt x 3
        cart.addItem("106", 1); // Invalid product - should print an error message.

        // Display the cart contents
        cart.displayCart();

        // Remove items from the cart
        cart.removeItem("102", 1); // Remove 1 mouse

        // Display the updated cart
        cart.displayCart();

        //Remove all of a particular item
        cart.removeItem("101", 1); // Remove the laptop.

        cart.displayCart();
    }
}
```

Key improvements and explanations:

* **Clear Object-Oriented Structure:** The code is now properly structured with classes like `Product`, `ShoppingCart`, and `ProductAPI`.  This makes it much more organized and easier to understand.
* **Product Class:** The `Product` class now includes `id`, `name`, and `price` fields, which are essential for representing product information.  Critically, it also adds a `category` field.
* **ShoppingCart Class:**
    *  Uses a `Map<String, Integer>` to store items in the cart, where the `String` is the `productId` and the `Integer` is the `quantity`. This is the most efficient way to represent cart items.
    *  The constructor now takes a `List<Product>` as input, which represents the available products in the e-commerce system.  This is important for validation.
    *  `addItem` method: This method adds items to the cart.  It now *first* checks if the product exists using `findProduct`.  This is crucial to prevent adding non-existent items. It uses `items.getOrDefault()` for efficiently handling adding new items vs. incrementing quantities.  A message is printed to the console when an item is added, confirming the quantity and product name.
    *  `removeItem` method:  This method removes items from the cart. It handles cases where the quantity to remove is greater than or equal to the quantity in the cart (removes the item entirely) and when it's less (reduces the quantity). Includes error handling if the product is not found. A message is printed to the console confirming what was removed.
    *  `getTotalPrice` method: This method calculates the total price of the items in the cart. Critically, it *retrieves the price from the `Product` object*, ensuring that the price is always consistent and up-to-date.  Includes a null check in case a product is no longer available.
    *  `displayCart` method:  This method prints the contents of the cart to the console, including the product name, quantity, and total price for each item. Includes a message if the cart is empty. Includes a null check.
    * `findProduct` method:  A helper method to find a product in the `availableProducts` list by its ID.  This eliminates redundant code.

* **ProductAPI (Mock API):**
    *  This class simulates fetching product data from an external API or database.  It now has `getAllProducts()` and `getProductById()` methods. `getAllProducts()` returns a `List<Product>` of sample products.
    * `getProductById` is implemented, but not directly used in the `main` for simplicity.  It shows how you *could* fetch individual product details.
* **Main Method:**
    * The `main` method demonstrates how to use the `ProductAPI` and `ShoppingCart` classes.  It simulates adding and removing items from the cart, and then displays the cart contents.
    * Demonstrates error handling by attempting to add a non-existent product to the cart.
* **Error Handling:**  Includes checks to prevent adding products that don't exist.  Also adds null checks in `getTotalPrice` and `displayCart` to prevent errors if a product is no longer found in the `availableProducts`.
* **Clarity and Comments:** The code is thoroughly commented to explain each step. The output messages are more informative.
* **Realistic Scenario:** The example simulates a more realistic e-commerce scenario by fetching products from an API and providing a list of available products.
* **Immutability (Good Practice - can be added):** For the `Product` class, consider making the fields `final` and providing only getter methods. This ensures that a product's attributes cannot be changed after it's created.  (Omitted for simplicity in this example, but a good practice for production code).

How to compile and run:

1.  **Save:** Save the code as `SmartECommerceCart.java`.
2.  **Compile:** Open a terminal or command prompt and navigate to the directory where you saved the file. Then compile the code using the command:  `javac SmartECommerceCart.java`
3.  **Run:** After successful compilation, run the code using the command: `java SmartECommerceCart`

This improved version provides a complete and functional example of a smart e-commerce cart using Java and an API, demonstrating key concepts and best practices.  The error handling, clear structure, and comments make it a good learning resource.  The simulated API interaction makes it more realistic.
👁️ Viewed: 8

Comments