当前位置:首页 > 行业动态 > 正文

java简单的购物车代码

java,import java.util.ArrayList;,import java.util.List;,,class Product {, String name;, double price;,, public Product(String name, double price) {, this.name = name;, this.price = price;, },},,class ShoppingCart {, List products;,, public ShoppingCart() {, products = new ArrayList();, },, public void addProduct(Product product) {, products.add(product);, },, public double getTotalPrice() {, double total = 0;, for (Product product : products) {, total += product.price;, }, return total;, },},,public class Main {, public static void main(String[] args) {, ShoppingCart cart = new ShoppingCart();, cart.addProduct(new Product("苹果", 5.0));, cart.addProduct(new Product("香蕉", 3.0));, System.out.println("购物车总价: " + cart.getTotalPrice());, },},

我们需要创建一个购物车类(ShoppingCart),用于存储商品信息,我们需要创建一个商品类(Product),用于表示商品,接下来,我们将实现购物车类中的方法,如添加商品、删除商品、计算总价等。

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 void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

2、创建购物车类(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 calculateTotalPrice() {
        double totalPrice = 0;
        for (Product product : products) {
            totalPrice += product.getPrice() * product.getQuantity();
        }
        return totalPrice;
    }
}

3、使用购物车类(ShoppingCart)

public class Main {
    public static void main(String[] args) {
        // 创建商品对象
        Product product1 = new Product("苹果", 5.0, 10);
        Product product2 = new Product("香蕉", 3.0, 5);
        // 创建购物车对象
        ShoppingCart shoppingCart = new ShoppingCart();
        // 将商品添加到购物车
        shoppingCart.addProduct(product1);
        shoppingCart.addProduct(product2);
        // 计算购物车中商品的总价
        double totalPrice = shoppingCart.calculateTotalPrice();
        System.out.println("购物车中商品的总价为:" + totalPrice);
    }
}

运行上述代码,将输出购物车中商品的总价。

0