import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class BeverageVendingMachine { private List<Beverage> beverages; private int balance; private List<String> salesLog; private Scanner scanner; public BeverageVendingMachine() { beverages = new ArrayList<>(); balance = 0; salesLog = new ArrayList<>(); scanner = new Scanner(System.in); } public void initializeProducts() { beverages.add(new Beverage("Coke", 2)); beverages.add(new Beverage("Sprite", 2)); beverages.add(new Beverage("Fanta", 2)); } public void sellProduct(int index) { Beverage selectedBeverage = beverages.get(index); if (selectedBeverage.getPrice() <= balance) { balance -= selectedBeverage.getPrice(); salesLog.add(selectedBeverage.getName()); System.out.println("You have bought " + selectedBeverage.getName() + "."); printReceipt(selectedBeverage); } else { System.out.println("Please insert more coins."); } } public void insertCoin(int amount) { balance += amount; System.out.println("You have inserted " + amount + " cents."); } public void returnCoins() { System.out.println("You have returned " + balance + " cents."); balance = 0; } public void printReceipt(Beverage beverage) { System.out.println("---------------"); System.out.println("Receipt:"); System.out.println(beverage.getName() + ": " + beverage.getPrice() + " cents"); System.out.println("Balance: " + balance + " cents"); System.out.println("---------------"); } public void printSalesLog() { System.out.println("Sales log:"); for (String item : salesLog) { System.out.println(item); } } public void run() { initializeProducts(); showMenu(); } public void showMenu() { System.out.println("Menu:"); for (int i = 0; i < beverages.size(); i++) { Beverage item = beverages.get(i); System.out.println(i + ". " + item.getName() + ": " + item.getPrice() + " cents"); } System.out.println("Please insert coins or enter 'r' to return coins:"); String input = scanner.nextLine(); if (input.equals("r")) { returnCoins(); } else { try { int index = Integer.parseInt(input); if (index >= 0 && index < beverages.size()) { sellProduct(index); } else { System.out.println("Invalid input."); } } catch (NumberFormatException e) { System.out.println("Invalid input."); } } showMenu(); }}class Beverage { private String name; private int price; public Beverage(String name, int price) { this.name = name; this.price = price; } public String getName() { return name; } public int getPrice() { return price; }}
时间: 2024-02-14 10:32:40 浏览: 70
java代码-import java.util.Scanner;
5星 · 资源好评率100%
这是一个简单的饮料自动售货机的Java代码。它通过BeverageVendingMachine类实现,该类包含了一些方法,如initializeProducts()、sellProduct()、insertCoin()、returnCoins()、printReceipt()、printSalesLog()和showMenu(),用于初始化售货机的产品、售出产品、插入硬币、退回硬币、打印收据、打印销售记录和显示菜单。该代码还包括一个Beverage类,用于表示饮料的名称和价格。该代码采用控制台输入和输出,可以在Java编译器或命令行界面中运行。
阅读全文