答案:通过定义Item类和ShoppingCart类,使用ArrayList管理商品,实现添加、删除、修改和统计功能。示例代码展示了商品合并、数量更新及总价计算,适用于学习和小型项目。

在Java中实现一个简易的购物车统计功能,可以通过面向对象的方式建模商品和购物车,结合集合类来管理商品数据。下面是一个简单但实用的实现方式。
定义商品类(Item)
每个商品应包含名称、单价和数量等基本信息。
public class Item {
private String name;
private double price; // 单价
private int quantity; // 数量
public Item(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
// 计算该商品小计
public double getSubtotal() {
return price * quantity;
}
@Override
public String toString() {
return name + " - ¥" + price + " × " + quantity + " = ¥" + getSubtotal();
}}
创建购物车类(ShoppingCart)
使用ArrayList存储商品,提供添加、删除、修改数量和统计总价的方法。
立即学习“Java免费学习笔记(深入)”;
BJXShop网上购物系统是一个高效、稳定、安全的电子商店销售平台,经过近三年市场的考验,在中国网购系统中属领先水平;完善的订单管理、销售统计系统;网站模版可DIY、亦可导入导出;会员、商品种类和价格均实现无限等级;管理员权限可细分;整合了多种在线支付接口;强有力搜索引擎支持... 程序更新:此版本是伴江行官方商业版程序,已经终止销售,现于免费给大家使用。比其以前的免费版功能增加了:1,整合了论坛
import java.util.ArrayList; import java.util.List;public class ShoppingCart { private List
- items;
public ShoppingCart() { items = new ArrayListzuojiankuohaophpcnyoujiankuohaophpcn(); } // 添加商品,如果已存在则增加数量 public void addItem(Item newItem) { for (Item item : items) { if (item.getName().equals(newItem.getName())) { item.setQuantity(item.getQuantity() + newItem.getQuantity()); return; } } items.add(new Item(newItem.getName(), newItem.getPrice(), newItem.getQuantity())); } // 从购物车中移除商品 public boolean removeItem(String itemName) { return items.removeIf(item -> item.getName().equals(itemName)); } // 修改商品数量 public boolean updateQuantity(String itemName, int quantity) { for (Item item : items) { if (item.getName().equals(itemName)) { item.setQuantity(quantity); return true; } } return false; } // 计算总金额 public double getTotal() { double total = 0; for (Item item : items) { total += item.getSubtotal(); } return total; } // 显示购物车内容 public void display() { if (items.isEmpty()) { System.out.println("购物车为空。"); } else { System.out.println("购物车商品列表:"); for (Item item : items) { System.out.println(item); } System.out.println("总计:¥" + getTotal()); } }}
测试购物车功能
编写主程序测试添加商品、修改、删除和统计功能。
public class CartTest {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.addItem(new Item("苹果", 5.0, 3));
cart.addItem(new Item("香蕉", 3.5, 2));
cart.addItem(new Item("苹果", 5.0, 2)); // 合并数量
cart.display();
// 修改数量
cart.updateQuantity("香蕉", 5);
System.out.println("\n修改香蕉数量为5后:");
cart.display();
// 删除商品
cart.removeItem("苹果");
System.out.println("\n删除苹果后:");
cart.display();
}}
这个实现适合学习或小型项目使用。它封装了基本操作,代码清晰,易于扩展。如需更复杂功能(如库存校验、优惠计算),可在现有结构上继续完善。基本上就这些。









