Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Console-Based Shopping Cart System in Java Using OOP

Tech 1

Class Design

The system consists of three core clases: User, Item, and a driver class ShoppingApp. The User class stores login credentials and personal details. The Item class represents products with identifiers, names, quantities, prices, and computed totals. The main application manages user rgeistration, authentication, and shopping cart operations via console input.

User Class

public class User {
    private String username;
    private String password;
    private String fullName;

    public User(String username, String password, String fullName) {
        this.username = username;
        this.password = password;
        this.fullName = fullName;
    }

    // Getters and setters
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }

    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }

    public String getFullName() { return fullName; }
    public void setFullName(String fullName) { this.fullName = fullName; }
}

Item Class

public class Item {
    private String id;
    private String name;
    private int quantity;
    private double unitPrice;

    public Item(String id, String name, int quantity, double unitPrice) {
        this.id = id;
        this.name = name;
        this.quantity = quantity;
        this.unitPrice = unitPrice;
    }

    public double getTotalPrice() {
        return quantity * unitPrice;
    }

    // Getters
    public String getId() { return id; }
    public String getName() { return name; }
    public int getQuantity() { return quantity; }
    public double getUnitPrice() { return unitPrice; }

    @Override
    public String toString() {
        return String.format("%s\t%s\t%d\t%.2f\t%.2f", 
            id, name, quantity, unitPrice, getTotalPrice());
    }
}

Main Application Logic

import java.util.*;

public class ShoppingApp {
    private static final Map<String, User> registeredUsers = new HashMap<>();
    private static final List<Item> cart = new ArrayList<>();
    private static final Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        boolean running = true;
        while (running) {
            System.out.println("------------------ Shopping Mall ------------------");
            System.out.println("1. Register");
            System.out.println("2. Login");
            System.out.print("Choose an option: ");
            int choice = input.nextInt();

            switch (choice) {
                case 1 -> registerUser();
                case 2 -> {
                    User currentUser = authenticateUser();
                    if (currentUser != null) {
                        manageCart(currentUser);
                    }
                }
                default -> System.out.println("Invalid option.");
            }
        }
    }

    private static void registerUser() {
        System.out.print("Enter username: ");
        String username = input.next();
        if (registeredUsers.containsKey(username)) {
            System.out.println("Username already exists.");
            return;
        }
        System.out.print("Enter password: ");
        String password = input.next();
        System.out.print("Enter full name: ");
        String fullName = input.next();
        registeredUsers.put(username, new User(username, password, fullName));
        System.out.println("Registration successful for " + username + "!");
    }

    private static User authenticateUser() {
        System.out.print("Enter username: ");
        String username = input.next();
        System.out.print("Enter password: ");
        String password = input.next();

        User user = registeredUsers.get(username);
        if (user != null && user.getPassword().equals(password)) {
        	System.out.println("Login successful, welcome " + user.getFullName() + "!");
            return user;
        } else {
            System.out.println("Invalid credentials or unregistered user.");
            return null;
        }
    }

    private static void manageCart(User user) {
        boolean shopping = true;
        while (shopping) {
            System.out.println("\n1. Add item to cart");
            System.out.println("2. View item by ID");
            System.out.println("3. View all items in cart");
            System.out.println("4. Checkout and exit");
            System.out.print("Select action: ");
            int action = input.nextInt();

            switch (action) {
                case 1 -> addItem();
                case 2 -> viewItemById();
                case 3 -> displayCart();
                case 4 -> {
                    System.out.println("Thank you for shopping!");
                    shopping = false;
                }
                default -> System.out.println("Invalid choice.");
            }
        }
    }

    private static void addItem() {
        System.out.print("Enter item ID: ");
        String id = input.next();
        System.out.print("Enter item name: ");
        String name = input.next();
        System.out.print("Enter quantity: ");
        int qty = input.nextInt();
        System.out.print("Enter unit price: ");
        double price = input.nextDouble();
        cart.add(new Item(id, name, qty, price));
        System.out.println("Item added to cart.");
    }

    private static void viewItemById() {
        System.out.print("Enter item ID: ");
        String id = input.next();
        Optional<Item> found = cart.stream().filter(item -> item.getId().equals(id)).findFirst();
        if (found.isPresent()) {
            System.out.println("ID\tName\tQty\tPrice\tTotal");
            System.out.println(found.get());
        } else {
            System.out.println("Item not found in cart.");
        }
    }

    private static void displayCart() {
        if (cart.isEmpty()) {
            System.out.println("Cart is empty.");
            return;
        }
        System.out.println("ID\tName\tQty\tPrice\tTotal");
        double total = 0;
        for (Item item : cart) {
            System.out.println(item);
            total += item.getTotalPrice();
        }
        System.out.printf("Total amount: %.2f\n", total);
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.