用java实现购物车添加购物功能
时间: 2023-09-30 09:12:25 浏览: 185
shopcookies_java_购物_
当然可以!下面是一个简单的示例代码,用Java实现购物车的添加商品功能:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
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 double getPrice() {
return price;
}
}
class ShoppingCart {
private List<Product> products;
public ShoppingCart() {
products = new ArrayList<>();
}
public void addProduct(Product product) {
products.add(product);
}
public void displayCart() {
System.out.println("Shopping Cart:");
for (Product product : products) {
System.out.println(product.getName() + " - $" + product.getPrice());
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ShoppingCart shoppingCart = new ShoppingCart();
boolean shopping = true;
while (shopping) {
System.out.println("Enter product name (or 'exit' to finish shopping):");
String productName = scanner.nextLine();
if (productName.equals("exit")) {
shopping = false;
break;
}
System.out.println("Enter product price:");
double productPrice = scanner.nextDouble();
scanner.nextLine(); // Consume the remaining newline character
Product product = new Product(productName, productPrice);
shoppingCart.addProduct(product);
}
shoppingCart.displayCart();
}
}
```
这段代码实现了一个简单的购物车程序。用户可以逐个输入商品名称和价格,程序将商品添加到购物车中。当用户输入"exit"时,程序结束,并展示购物车中的商品列表及其价格。
希望这个示例能帮到你!如果你还有其他问题,请随时提问。
阅读全文