登录
首页 >  文章 >  java教程

Java购物车实现步骤详解

时间:2025-09-24 14:54:50 445浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习文章相关编程知识。下面本篇文章就来带大家聊聊《Java简易购物车实现教程》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

答案:程序实现了商品管理与购物车操作。定义Product类表示商品,包含ID、名称和价格;CartItem类记录商品及数量,计算条目总价;ShoppingCart类用HashMap存储条目,支持添加、更新、删除和显示购物车内容;主程序创建商品并测试添加、修改、删除功能,输出每次操作后的购物车状态,展示面向对象设计与集合应用。

如何用Java写一个简易购物车程序

写一个简易购物车程序,核心是管理商品和用户的购买行为。Java可以通过类来模拟商品、购物车条目和购物车本身。下面是一个结构清晰、易于理解的实现方式。

1. 定义商品类(Product)

每个商品有名称、价格和唯一ID。

class Product {
    private String id;
    private String name;
    private double price;
<pre class="brush:java;toolbar:false;">public Product(String id, String name, double price) {
    this.id = id;
    this.name = name;
    this.price = price;
}

// Getter方法
public String getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }

@Override
public String toString() {
    return "ID: " + id + ", 名称: " + name + ", 价格: ¥" + price;
}

}

2. 定义购物车条目类(CartItem)

表示购物车中某商品及其数量。

class CartItem {
    private Product product;
    private int quantity;
<pre class="brush:java;toolbar:false;">public CartItem(Product product, int quantity) {
    this.product = product;
    this.quantity = quantity;
}

public Product getProduct() { return product; }
public int getQuantity() { return quantity; }

public void setQuantity(int quantity) { this.quantity = quantity; }

public double getTotalPrice() {
    return product.getPrice() * quantity;
}

@Override
public String toString() {
    return product.getName() + " × " + quantity + " = ¥" + getTotalPrice();
}

}

3. 定义购物车类(ShoppingCart)

使用HashMap存储商品ID到条目的映射,支持添加、删除、修改数量和计算总价。

import java.util.HashMap;
import java.util.Map;
<p>class ShoppingCart {
private Map<String, CartItem> items;</p><pre class="brush:java;toolbar:false;">public ShoppingCart() {
    items = new HashMap<>();
}

// 添加商品
public void addProduct(Product product, int quantity) {
    if (quantity <= 0) return;

    if (items.containsKey(product.getId())) {
        CartItem item = items.get(product.getId());
        item.setQuantity(item.getQuantity() + quantity);
    } else {
        items.put(product.getId(), new CartItem(product, quantity));
    }
}

// 更新商品数量
public void updateQuantity(String productId, int quantity) {
    if (items.containsKey(productId)) {
        if (quantity <= 0) {
            items.remove(productId);
        } else {
            items.get(productId).setQuantity(quantity);
        }
    }
}

// 移除商品
public void removeProduct(String productId) {
    items.remove(productId);
}

// 显示购物车内容
public void display() {
    if (items.isEmpty()) {
        System.out.println("购物车为空。");
        return;
    }
    System.out.println("\n--- 购物车内容 ---");
    for (CartItem item : items.values()) {
        System.out.println(item);
    }
    System.out.println("总计: ¥" + getTotalPrice());
}

// 获取总金额
public double getTotalPrice() {
    return items.values().stream()
               .mapToDouble(CartItem::getTotalPrice)
               .sum();
}

}

4. 主程序测试

创建商品,操作购物车,查看结果。

public class SimpleShoppingCart {
    public static void main(String[] args) {
        // 创建商品
        Product p1 = new Product("P001", "苹果", 5.0);
        Product p2 = new Product("P002", "香蕉", 3.5);
        Product p3 = new Product("P003", "橙子", 4.0);
<pre class="brush:java;toolbar:false;">    // 创建购物车
    ShoppingCart cart = new ShoppingCart();

    // 添加商品
    cart.addProduct(p1, 2); // 苹果 ×2
    cart.addProduct(p2, 1); // 香蕉 ×1
    cart.addProduct(p1, 3); // 再加3个苹果 → 共5个

    cart.display();

    // 修改数量
    cart.updateQuantity("P002", 4); // 香蕉改为4个
    cart.display();

    // 删除商品
    cart.removeProduct("P003"); // 橙子不在购物车,无影响
    cart.removeProduct("P001"); // 删除苹果
    cart.display();
}

}

运行后你会看到购物车内容逐步变化,包括添加、更新和删除操作的结果。

基本上就这些。这个简易购物车适合学习面向对象编程和集合操作。你可以在此基础上扩展功能,比如加入库存检查、用户登录、持久化保存等。

本篇关于《Java购物车实现步骤详解》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>