用Java写超市购物系统的代码
时间: 2023-05-14 15:06:38 浏览: 743
非常感谢您的提问,以下是一个简单的超市购物系统的Java代码:
```
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Supermarket {
private Map<String, Double> products;
private Map<String, Integer> inventory;
public Supermarket() {
products = new HashMap<>();
inventory = new HashMap<>();
}
public void addProduct(String name, double price, int quantity) {
products.put(name, price);
inventory.put(name, quantity);
}
public void buyProduct(String name, int quantity) {
if (inventory.containsKey(name)) {
int currentQuantity = inventory.get(name);
if (currentQuantity >= quantity) {
inventory.put(name, currentQuantity - quantity);
double totalPrice = quantity * products.get(name);
System.out.println("购买成功!您购买了 " + quantity + " 个 " + name + ",总价为 " + totalPrice + " 元。");
} else {
System.out.println("购买失败!库存不足。");
}
} else {
System.out.println("购买失败!该商品不存在。");
}
}
public static void main(String[] args) {
Supermarket supermarket = new Supermarket();
supermarket.addProduct("苹果", 5.0, 10);
supermarket.addProduct("香蕉", 3.0, 20);
supermarket.addProduct("橙子", 4.0, 15);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("请输入您要购买的商品名称和数量(用空格隔开),输入 q 退出:");
String input = scanner.nextLine();
if (input.equals("q")) {
break;
}
String[] parts = input.split(" ");
if (parts.length != 2) {
System.out.println("输入格式错误,请重新输入。");
continue;
}
String name = parts[0];
int quantity;
try {
quantity = Integer.parseInt(parts[1]);
} catch (NumberFormatException e) {
System.out.println("数量输入错误,请重新输入。");
continue;
}
supermarket.buyProduct(name, quantity);
}
}
}
```
希望这个代码能够帮到您!
阅读全文