以下是一个简单的购物车代码示例,使用Java编写,这个购物车可以添加商品、删除商品和计算总价。
import java.util.ArrayList;
import java.util.List;
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 void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
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();
}
return totalPrice;
}
}
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
// 添加商品
Product product1 = new Product("苹果", 5.0);
Product product2 = new Product("香蕉", 3.0);
Product product3 = new Product("橙子", 4.0);
cart.addProduct(product1);
cart.addProduct(product2);
cart.addProduct(product3);
// 计算总价
double totalPrice = cart.calculateTotalPrice();
System.out.println("购物车总价: " + totalPrice);
// 删除商品
cart.removeProduct(product2);
// 重新计算总价
totalPrice = cart.calculateTotalPrice();
System.out.println("删除香蕉后的购物车总价: " + totalPrice);
}
}
在这个示例中,我们创建了两个类:Product 和 ShoppingCart。Product 类表示一个商品,包含商品名称和价格。ShoppingCart 类表示购物车,包含一个商品列表,以及添加商品、删除商品和计算总价的方法。
添加商品到购物车
我们可以使用addProduct方法将商品添加到购物车中:
ShoppingCart cart = new ShoppingCart();
Product product1 = new Product("苹果", 5.0);
cart.addProduct(product1);
从购物车中删除商品
我们使用removeProduct方法从购物车中删除商品:
ShoppingCart cart = new ShoppingCart();
Product product1 = new Product("苹果", 5.0);
cart.addProduct(product1);
...
cart.removeProduct(product1);
计算购物车的总价
我们使用calculateTotalPrice方法计算购物车中所有商品的总价:
ShoppingCart cart = new ShoppingCart();
Product product1 = new Product("苹果", 5.0);
cart.addProduct(product1);
...
double totalPrice = cart.calculateTotalPrice();
在 main 方法中,我们创建了一个购物车对象,然后添加了三个商品,接着,我们计算并输出购物车的总价,我们从购物车中删除了一个商品,并重新计算并输出购物车的总价。
希望这个简单的购物车代码对您有所帮助!如果您有任何关于Java编程的问题,请随时在下方留言区中提出,我们将竭诚为您解答!
请记得关注我们的博客,获取更多有用的代码和技术知识!感谢您的阅读!
注:本文所使用的图片均来自 Unsplash API。
感谢观看!
评论留言