咖啡自动售货机系统设计的Java代码
时间: 2023-09-22 22:15:30 浏览: 95
以下是一个简单的咖啡自动售货机系统的Java代码示例:
```java
import java.util.Scanner;
public class CoffeeVendingMachine {
private int coffeeCount = 10;
private int sugarCount = 10;
private int milkCount = 10;
private int moneyEarned = 0;
private int coffeePrice = 5;
public void start() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Welcome to the Coffee Vending Machine");
System.out.println("1. Buy coffee");
System.out.println("2. Check coffee count");
System.out.println("3. Check sugar count");
System.out.println("4. Check milk count");
System.out.println("5. Check money earned");
System.out.println("6. Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
buyCoffee();
break;
case 2:
checkCoffeeCount();
break;
case 3:
checkSugarCount();
break;
case 4:
checkMilkCount();
break;
case 5:
checkMoneyEarned();
break;
case 6:
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
private void buyCoffee() {
if (coffeeCount == 0) {
System.out.println("Sorry, no coffee available.");
return;
}
if (sugarCount == 0) {
System.out.println("Sorry, no sugar available.");
return;
}
if (milkCount == 0) {
System.out.println("Sorry, no milk available.");
return;
}
System.out.println("Please insert " + coffeePrice + " dollars.");
Scanner scanner = new Scanner(System.in);
int money = scanner.nextInt();
if (money < coffeePrice) {
System.out.println("Not enough money inserted.");
return;
}
coffeeCount--;
sugarCount--;
milkCount--;
moneyEarned += coffeePrice;
System.out.println("Enjoy your coffee!");
}
private void checkCoffeeCount() {
System.out.println("Coffee count: " + coffeeCount);
}
private void checkSugarCount() {
System.out.println("Sugar count: " + sugarCount);
}
private void checkMilkCount() {
System.out.println("Milk count: " + milkCount);
}
private void checkMoneyEarned() {
System.out.println("Money earned: " + moneyEarned);
}
}
```
这个代码示例中,我们定义了一个`CoffeeVendingMachine`类,其中包含了自动售货机的各种属性和方法。在`start`方法中,我们使用一个循环来不断接收用户输入的选择,并根据选择调用相应的方法。在`buyCoffee`方法中,我们首先判断是否有足够的咖啡、糖和牛奶,如果有,则要求用户插入硬币,如果硬币不足,则返回错误信息;如果硬币充足,则减少咖啡、糖和牛奶的数量,并增加售货机的收入。在其他方法中,我们只是简单地返回相应的属性值。
阅读全文