答案:通过面向对象设计实现购物车核心功能,定义Product类表示商品,CartItem类记录商品与数量,ShoppingCart类管理购物车增删改查及总价计算,Main类测试添加、合并、移除商品并展示结果,适用于Java基础学习。

在Java中实现一个简单的购物车项目,核心是管理商品和用户选购行为。不需要数据库或前端界面的情况下,可以用面向对象的方式构建基础逻辑。以下是清晰的实现思路和代码结构。
定义商品类(Product)
每个商品应有基本信息,如名称、价格和ID。
public class Product {
private int id;
private String name;
private double price;
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
// Getter方法
public int getId() { return id; }
public String getName() { return name; }
public double getPrice() { return price; }
@Override
public String toString() {
return "ID: " + id + ", 名称: " + name + ", 价格: ¥" + price;
}}
定义购物车项类(CartItem)
表示购物车中的每一项,包含商品和数量。
立即学习“Java免费学习笔记(深入)”;
public class CartItem {
private Product product;
private int quantity;
public CartItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public Product getProduct() { return product; }
public int getQuantity() { return quantity; }
public double getTotalPrice() { return product.getPrice() * quantity; }
public void setQuantity(int quantity) { this.quantity = quantity; }}
实现购物车类(ShoppingCart)
使用ArrayList存储购物车项,提供添加、删除、修改和结算功能。
import java.util.ArrayList; import java.util.List;public class ShoppingCart { private List
items; public ShoppingCart() { items = new ArrayListzuojiankuohaophpcnyoujiankuohaophpcn(); } // 添加商品到购物车 public void addItem(Product product, int quantity) { for (CartItem item : items) { if (item.getProduct().getId() == product.getId()) { item.setQuantity(item.getQuantity() + quantity); System.out.println("已更新 " + product.getName() + " 的数量"); return; } } items.add(new CartItem(product, quantity)); System.out.println("已添加 " + product.getName() + " 到购物车"); } // 从购物车移除商品 public void removeItem(int productId) { items.removeIf(item -> item.getProduct().getId() == productId); System.out.println("已从购物车移除ID为 " + productId + " 的商品"); } // 计算总金额 public double getTotal() { return items.stream().mapToDouble(CartItem::getTotalPrice).sum(); } // 显示购物车内容 public void viewCart() { if (items.isEmpty()) { System.out.println("购物车为空"); return; } System.out.println("\n--- 购物车内容 ---"); for (CartItem item : items) { System.out.println(item.getProduct() + " | 数量: " + item.getQuantity() + " | 小计: ¥" + String.format("%.2f", item.getTotalPrice())); } System.out.println("总计: ¥" + String.format("%.2f", getTotal())); }}
测试购物车功能
编写主程序验证购物车行为。
public class Main {
public static void main(String[] args) {
// 创建商品
Product p1 = new Product(1, "笔记本电脑", 5999.0);
Product p2 = new Product(2, "鼠标", 89.0);
Product p3 = new Product(3, "键盘", 299.0);
// 创建购物车
ShoppingCart cart = new ShoppingCart();
// 添加商品
cart.addItem(p1, 1);
cart.addItem(p2, 2);
cart.addItem(p2, 1); // 增加鼠标数量
cart.addItem(p3, 1);
// 查看购物车
cart.viewCart();
// 移除商品
cart.removeItem(2);
cart.viewCart();
}}
运行后会看到添加、合并数量、移除和重新计算总价的过程。这个实现适合学习Java基础语法、封装、集合操作和简单业务逻辑处理。后续可扩展功能如库存检查、持久化保存、折扣计算等。基本上就这些,不复杂但容易忽略细节比如重复商品的合并。










