知识问答
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
“
我们需要创建一个购物车类(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); }}
运行上述代码,将输出购物车中商品的总价。
java购物车代码上一篇:js如何替换html标签的内容
下一篇:android图片上传_上传图片
最新文章
- 安徽短信提供商_安徽管局要求
- c#managementclass
- 常见的服务器加固方法,保护服务器的方法有哪些?
- administrator密码忘记_忘记密码
- 微信小程序究竟是什么,微信小程序的定义及特点
- sql中execute的作用是什么
- 快手准考证怎么弄
- 免费域名解析服务器软件有哪些
- asp与sql数据库连接_ASP报告信息
- 国内有哪些比较知名的wordpress主题开发网站
- ASP生成WML_生成
- 用sharepoint designer制作网页的教程
- 安装wget_GP Vnt1裸金属服务器的Docker模式环境搭建
- 新加坡vps评测的方法是什么
- ASP数据岛操作类_ASP报告信息
- 美国VPS哪个好,*几款优质的美国VPS
- 怎样处理多易拍文件拍摄仪一些常见的问题
- asp网站内容管理系统_ASP报告信息
- 永久免费香港虚拟空间怎么申请
- asp缓存类_缓存类接口