用Java写一个购物系统
时间: 2024-01-03 22:04:54 浏览: 24
好的,我可以为您提供一个简单的购物系统的Java代码示例,以下是代码:
```java
import java.util.*;
public class ShoppingCart {
private static Map<String, Double> products = new HashMap<String, Double>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
products.put("apple", 0.5);
products.put("banana", 0.3);
products.put("orange", 0.4);
products.put("pear", 0.35);
List<String> cart = new ArrayList<String>();
while (true) {
System.out.println("请选择要购买的商品: ");
String item = scanner.next().toLowerCase();
if (item.equals("quit")) {
break;
}
if (!products.containsKey(item)) {
System.out.println("商品不存在,请重新选择!");
continue;
}
cart.add(item);
System.out.println(item + "已添加到购物车");
}
System.out.println("您的购物车中有以下商品:");
double total = 0;
for (String item : cart) {
double price = products.get(item);
System.out.println(item + " - " + price);
total += price;
}
System.out.println("总价: " + total);
scanner.close();
}
}
```
该代码实现了一个简单的购物系统,包括商品列表、添加商品到购物车、显示购物车商品列表以及计算总价等功能。
运行代码后,您可以输入要购买的商品名称,程序会将该商品添加到购物车中并显示购物车中的商品列表和总价。如果输入“quit”,程序会结束运行。