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

在Java中实现购物车的商品添加与删除功能,核心是管理一个商品列表,支持增删操作,并可计算总价。下面是一个简单但实用的实现方式,适合初学者理解基本逻辑。
每个商品应包含基本信息,如名称、价格和数量。
public class Product {
private String name;
private double price;
private int quantity;
<pre class='brush:java;toolbar:false;'>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;
}}
使用ArrayList存储商品,提供添加、删除和显示方法。
立即学习“Java免费学习笔记(深入)”;
import java.util.ArrayList;
import java.util.List;
<p>public class ShoppingCart {
private List<Product> items;</p><pre class='brush:java;toolbar:false;'>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;
}}
编写主程序测试添加、删除和展示功能。
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
<pre class='brush:java;toolbar:false;'> 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();
}}
运行结果会显示商品添加、合并、删除及总价计算过程,验证功能正确性。
实际项目中可进一步优化:
基本上就这些,不复杂但容易忽略细节。掌握这个结构后,可以轻松集成到Web应用或GUI界面中。
以上就是如何使用Java实现购物车商品添加与删除的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号