定义商品类包含名称、价格、数量及getter/setter方法;2. 购物车类用ArrayList存储商品,实现添加时合并同名商品、按名称删除、显示和计算总价功能;3. 测试类验证添加、合并、删除和展示流程;4. 可扩展使用Map提升性能、增加库存校验与数据持久化。

在Java中实现购物车的商品添加与删除功能,核心是管理一个商品列表,支持增删操作,并可计算总价。下面是一个简单但实用的实现方式,适合初学者理解基本逻辑。
1. 定义商品类(Product)
每个商品应包含基本信息,如名称、价格和数量。
public class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
// Getter 和 Setter 方法
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "商品: " + name + ", 价格: " + price + ", 数量: " + quantity;
}}
Ztoy网络商铺多用户版
在原版的基础上做了一下修正:增加1st在线支付功能与论坛用户数据结合,vip也可与论坛相关,增加互动性vip会员的全面修正评论没有提交正文的问题特价商品的调用连接问题删掉了2个木马文件去掉了一个后门补了SQL注入补了一个过滤漏洞浮动价不能删除的问题不能够搜索问题收藏时放入购物车时出错点放入购物车弹出2个窗口修正定单不能删除问题VIP出错问题主题添加问题商家注册页导航连接问题添加了导航FLASH源文
下载
2. 实现购物车类(ShoppingCart)
使用ArrayList存储商品,提供添加、删除和显示方法。
立即学习“Java免费学习笔记(深入)”;
import java.util.ArrayList; import java.util.List;public class ShoppingCart { private List
items; public ShoppingCart() { items = new ArrayList<>(); } // 添加商品 public void addProduct(Product product) { for (Product item : items) { if (item.getName().equals(product.getName())) { item.setQuantity(item.getQuantity() + product.getQuantity()); System.out.println("商品已合并到购物车:" + product.getName()); return; } } items.add(new Product(product.getName(), product.getPrice(), product.getQuantity())); System.out.println("商品已添加:" + product.getName()); } // 删除商品(按名称) public boolean removeProduct(String productName) { return items.removeIf(item -> item.getName().equals(productName)); } // 显示购物车内容 public void displayCart() { if (items.isEmpty()) { System.out.println("购物车为空!"); } else { System.out.println("购物车商品:"); for (Product item : items) { System.out.println(" " + item); } System.out.println("总计:" + getTotalPrice() + " 元"); } } // 计算总价 public double getTotalPrice() { double total = 0; for (Product item : items) { total += item.getPrice() * item.getQuantity(); } return total; }}
3. 测试购物车功能
编写主程序测试添加、删除和展示功能。
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
Product p1 = new Product("苹果", 5.0, 2);
Product p2 = new Product("香蕉", 3.0, 4);
Product p3 = new Product("苹果", 5.0, 1); // 同名商品,应合并
cart.addProduct(p1);
cart.addProduct(p2);
cart.addProduct(p3); // 苹果数量变为3
cart.displayCart();
cart.removeProduct("香蕉");
System.out.println("\n删除香蕉后:");
cart.displayCart();
}}
运行结果会显示商品添加、合并、删除及总价计算过程,验证功能正确性。
4. 注意事项与扩展建议
实际项目中可进一步优化:
- 使用Map
以商品名为键,提升查找效率 - 加入库存校验逻辑
- 支持修改商品数量
- 持久化购物车数据(如写入文件或数据库)
基本上就这些,不复杂但容易忽略细节。掌握这个结构后,可以轻松集成到Web应用或GUI界面中。









