Java 购物车示例代码:使用类和集合实现商品添加及价格计算
该代码实现了一个简单的购物车功能。
首先,定义了一个商品类('Product'),包含商品的名称、ID和价格,并提供了相应的getter和setter方法。
然后,定义了一个顾客类('Customer'),包含顾客的ID和购物车(以ArrayList
在主程序中,首先创建了两个商品对象('product1'和'product2'),然后创建了一个顾客对象('customer1')并将商品添加到购物车中。接着,通过遍历购物车中的商品,计算购物车内商品的总价。
最后,输出购物车内商品的总价。
import java.util.ArrayList;
// 商品类
class Product {
private String name;
private String id;
private double price;
public Product(String name, String id, double price) {
this.name = name;
this.id = id;
this.price = price;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
// 顾客类
class Customer {
private String id;
private ArrayList<Product> cart = new ArrayList<>();
public Customer(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void addToCart(Product product) {
cart.add(product);
}
public ArrayList<Product> getCart() {
return cart;
}
}
// 主程序
public class Main {
public static void main(String[] args) {
// 创建商品
Product product1 = new Product("商品1", "001", 100.0);
Product product2 = new Product("商品2", "002", 200.0);
// 创建顾客并添加商品到购物车
Customer customer1 = new Customer("C001");
customer1.addToCart(product1);
customer1.addToCart(product2);
// 计算购物车内商品总价
double total = 0;
for (Product product : customer1.getCart()) {
total += product.getPrice();
}
System.out.println("The total price of the items in the shopping cart is: " + total);
}
}
该代码示例展示了如何使用 Java 类和集合来模拟购物车的基本功能。通过定义商品类和顾客类,并使用 ArrayList 存储商品信息,我们可以实现商品的添加、获取以及计算总价等操作。
原文地址: https://www.cveoy.top/t/topic/m4Qy 著作权归作者所有。请勿转载和采集!