要实现一个Java购物车,你可以按照以下步骤进行操作:
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方法
}
ShoppingCart
类来表示购物车,该类包括购物车中的商品列表和一些操作方法。import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
private List<Product> products;
public ShoppingCart() {
products = new ArrayList<>();
}
public void addProduct(Product product) {
products.add(product);
}
public void removeProduct(Product product) {
products.remove(product);
}
public double getTotalPrice() {
double totalPrice = 0;
for (Product product : products) {
totalPrice += product.getPrice() * product.getQuantity();
}
return totalPrice;
}
public void printCart() {
for (Product product : products) {
System.out.println("商品名称:" + product.getName());
System.out.println("商品价格:" + product.getPrice());
System.out.println("商品数量:" + product.getQuantity());
System.out.println("--------------------");
}
System.out.println("总价:" + getTotalPrice());
}
}
public class Main {
public static void main(String[] args) {
Product product1 = new Product("商品1", 10.0, 2);
Product product2 = new Product("商品2", 20.0, 1);
Product product3 = new Product("商品3", 30.0, 3);
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.addProduct(product1);
shoppingCart.addProduct(product2);
shoppingCart.addProduct(product3);
shoppingCart.printCart();
}
}
以上代码实现了一个简单的Java购物车,你可以根据需求进行扩展和修改。