这次我们将实现一个简单的购物车系统。这个系统会使用List来存储购物车中的商品,使用Map来跟踪每种商品的数量,并允许用户添加和移除商品。
首先,我们定义一个Product类来表示购物车中的商品:
java复制代码
|
public class Product { |
|
private String name; |
|
private double price; |
|
|
|
public Product(String name, double price) { |
|
this.name = name; |
|
this.price = price; |
|
} |
|
|
|
public String getName() { |
|
return name; |
|
} |
|
|
|
public double getPrice() { |
|
return price; |
|
} |
|
|
|
@Override |
|
public String toString() { |
|
return "Product{" + |
|
"name='" + name + '\'' + |
|
", price=" + price + |
|
'}'; |
|
} |
|
} |
接下来,我们创建一个ShoppingCart类来管理购物车中的商品:
java复制代码
|
import java.util.ArrayList; |
|
import java.util.HashMap; |
|
import java.util.List; |
|
import java.util.Map; |
|
|
|
public class ShoppingCart { |
|
private List<Product> products; |
|
private Map<Product, Integer> quantityMap; |
|
|
|
public ShoppingCart() { |
|
products = new ArrayList<>(); |
|
quantityMap = new HashMap<>(); |
|
} |
|
|
|
public void addProduct(Product product) { |
|
if (quantityMap.containsKey(product)) { |
|
int quantity = quantityMap.get(product) + 1; |
|
quantityMap.put(product, quantity); |
|
} else { |
|
quantityMap.put(product, 1); |
|
products.add(product); |
|
} |
|
} |
|
|
|
public void removeProduct(Product product) { |
|
if (quantityMap.containsKey(product)) { |
|
int quantity = quantityMap.get(product) - 1; |
|
if (quantity == 0) { |
|
quantityMap.remove(product); |
|
products.remove(product); |
|
} else { |
|
quantityMap.put(product, quantity); |
|
} |
|
} |
|
} |
|
|
|
public double getTotalPrice() { |
|
double total = 0.0; |
|
for (Map.Entry<Product, Integer> entry : quantityMap.entrySet()) { |
|
Product product = entry.getKey(); |
|
int quantity = entry.getValue(); |
|
total += product.getPrice() * quantity; |
|
} |
|
return total; |
|
} |
|
|
|
public void displayCart() { |
|
System.out.println("购物车中的商品:"); |
|
for (Product product : products) { |
|
int quantity = quantityMap.get(product); |
|
System.out.println(product.getName() + " x " + quantity + " = " + (product.getPrice() * quantity) + " 元"); |
|
} |
|
System.out.println("总价: " + getTotalPrice() + " 元"); |
|
} |
|
} |
最后,我们在主函数中演示如何使用ShoppingCart:
java复制代码
|
public class Main { |
|
public static void main(String[] args) { |
|
ShoppingCart cart = new ShoppingCart(); |
|
|
|
// 添加商品到购物车 |
|
Product apple = new Product("苹果", 5.0); |
|
Product banana = new Product("香蕉", 3.0); |
|
cart.addProduct(apple); |
|
cart.addProduct(apple); |
|
cart.addProduct(banana); |
|
|
|
// 显示购物车内容 |
|
cart.displayCart(); |
|
|
|
// 移除一个商品 |
|
cart.removeProduct(apple); |
|
|
|
// 再次显示购物车内容 |
|
cart.displayCart(); |
|
} |
|
} |
这个示例演示了如何使用List来存储购物车中的商品对象,并使用Map来跟踪每种商品的数量。addProduct方法用于向购物车中添加商品,removeProduct方法用于从购物车中移除商品。getTotalPrice方法计算购物车中所有商品的总价,而displayCart方法则用于显示购物车的内容和总价。
这个购物车系统只是一个简单的示例,实际应用中可能需要考虑更多细节,比如库存管理、商品打折、用户身份验证等。