用Java代码写一个自动贩卖机 能够添加饮料 打印欢迎词 列出饮料信息 付钱挑饮料 交付饮料并从贩卖机中弹出(对应空位空出) 显示购买后找的钱 显示贩卖机余额
时间: 2023-05-24 13:04:44 浏览: 104
以下是一个简单的Java代码实现:
import java.util.HashMap;
import java.util.Scanner;
public class VendingMachine {
// 饮料库存数量
private static HashMap<String, Integer> drinkInventory = new HashMap<>();
// 饮料售价
private static HashMap<String, Integer> drinkPrice = new HashMap<>();
// 贩卖机余额
private static int balance = 0;
public static void main(String[] args) {
// 初始化饮料信息
drinkInventory.put("可乐", 10);
drinkInventory.put("雪碧", 10);
drinkPrice.put("可乐", 3);
drinkPrice.put("雪碧", 2);
System.out.println("欢迎使用自动贩卖机!");
while (true) {
System.out.println("请输入您要选择的操作:");
System.out.println("1. 添加饮料");
System.out.println("2. 查看饮料信息");
System.out.println("3. 购买饮料");
System.out.println("4. 退出");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
addDrink();
break;
case 2:
listDrinkInfo();
break;
case 3:
buyDrink();
break;
case 4:
System.out.println("欢迎下次再来!");
System.exit(0);
break;
default:
System.out.println("输入有误,请重新输入!");
break;
}
}
}
// 添加饮料
private static void addDrink() {
System.out.println("请输入要添加的饮料名称:");
Scanner scanner = new Scanner(System.in);
String drinkName = scanner.nextLine();
if (drinkInventory.containsKey(drinkName)) {
System.out.println("该饮料已存在,若需增加数量请选择购买饮料操作。");
return;
}
System.out.println("请输入饮料数量:");
int drinkCount = scanner.nextInt();
System.out.println("请输入饮料售价:");
int drinkPrice = scanner.nextInt();
drinkInventory.put(drinkName, drinkCount);
VendingMachine.drinkPrice.put(drinkName, drinkPrice);
System.out.println(drinkCount + " 瓶 " + drinkName + " 添加成功!");
}
// 查看饮料信息
private static void listDrinkInfo() {
System.out.println("当前贩卖机余额为:" + balance);
System.out.println("饮料名称\t饮料库存\t饮料单价");
for (String drinkName : drinkInventory.keySet()) {
System.out.println(drinkName + "\t\t" + drinkInventory.get(drinkName) + "\t\t" + drinkPrice.get(drinkName));
}
}
// 购买饮料
private static void buyDrink() {
System.out.println("请选择要购买的饮料:");
for (String drinkName : drinkInventory.keySet()) {
System.out.println(drinkName + " - 售价:" + drinkPrice.get(drinkName));
}
Scanner scanner = new Scanner(System.in);
String drinkName = scanner.nextLine();
if (!drinkInventory.containsKey(drinkName)) {
System.out.println("抱歉,该饮料不存在。");
return;
}
int drinkCount = drinkInventory.get(drinkName);
if (drinkCount == 0) {
System.out.println("抱歉,该饮料已卖完。");
return;
}
System.out.println("请输入支付金额:");
int money = scanner.nextInt();
if (money < drinkPrice.get(drinkName)) {
System.out.println("支付金额不足,购买失败。");
return;
}
int change = money - drinkPrice.get(drinkName);
System.out.println("购买成功,找零 " + change + " 元。");
balance += drinkPrice.get(drinkName);
drinkInventory.put(drinkName, drinkCount - 1);
System.out.println("请取走您的 " + drinkName + " 饮料。");
}
}
阅读全文