创建一个自动贩卖机 能够添加饮料 打印欢迎词 列出饮料信息 付钱挑饮料 交付饮料并从贩卖机中弹出(对应空位空出) 显示购买后找的钱 显示贩卖机余额 java完整代码
时间: 2023-05-24 21:02:40 浏览: 99
Java实现 自动贩卖/售货机 系统
5星 · 资源好评率100%
// 自动贩卖机类
public class VendingMachine {
private String[] drinks; // 饮料名称数组
private double[] prices; // 饮料价格数组
private int[] quantities; // 饮料数量数组
private double balance; // 贩卖机余额
// 构造方法,初始化饮料信息、数量和贩卖机余额
public VendingMachine(String[] drinks, double[] prices, int[] quantities, double balance) {
this.drinks = drinks;
this.prices = prices;
this.quantities = quantities;
this.balance = balance;
}
// 添加饮料
public void addDrink(String drink, double price, int quantity) {
String[] new_drinks = new String[drinks.length + 1];
double[] new_prices = new double[prices.length + 1];
int[] new_quantities = new int[quantities.length + 1];
for (int i = 0; i < drinks.length; i++) {
new_drinks[i] = drinks[i];
new_prices[i] = prices[i];
new_quantities[i] = quantities[i];
}
new_drinks[drinks.length] = drink;
new_prices[prices.length] = price;
new_quantities[quantities.length] = quantity;
drinks = new_drinks;
prices = new_prices;
quantities = new_quantities;
}
// 打印欢迎词和饮料信息
public void printInfo() {
System.out.println("欢迎使用自动贩卖机!");
System.out.println("本贩卖机提供以下饮料:");
for (int i = 0; i < drinks.length; i++) {
System.out.println((i + 1) + ". " + drinks[i] + " ¥" + prices[i] + " (还剩 " + quantities[i] + " 瓶)");
}
}
// 付钱挑饮料
public boolean buyDrink(int index, double money) {
if (index < 0 || index >= drinks.length) {
System.out.println("输入的饮料编号不正确!");
return false;
}
if (quantities[index] <= 0) {
System.out.println("抱歉,该饮料已售罄!");
return false;
}
if (money < prices[index]) {
System.out.println("您的金额不足!");
return false;
}
System.out.println("谢谢光临,您购买的是 " + drinks[index] + " !");
System.out.println("找您 " + (money - prices[index]) + " 元钱。");
quantities[index]--;
balance += prices[index];
return true;
}
// 显示贩卖机余额
public void showBalance() {
System.out.println("贩卖机余额为:¥" + balance);
}
// 主程序,测试自动贩卖机
public static void main(String[] args) {
// 初始化自动贩卖机
String[] drinks = {"可乐", "雪碧", "矿泉水"};
double[] prices = {3.0, 3.0, 2.0};
int[] quantities = {5, 5, 10};
double balance = 0.0;
VendingMachine vm = new VendingMachine(drinks, prices, quantities, balance);
// 添加新饮料
vm.addDrink("芬达", 3.5, 3);
// 打印欢迎词和饮料信息
vm.printInfo();
// 购买饮料
boolean success = vm.buyDrink(0, 5.0);
if (success) {
vm.showBalance();
}
// 再次打印欢迎词和饮料信息
vm.printInfo();
}
}
阅读全文