用java写一个程序,制作一个咖啡售卖机,用三个类
时间: 2023-06-19 17:02:51 浏览: 88
好的,下面是我给您提供的代码,共包含三个类:CoffeeMachine、Coffee和Customer。
CoffeeMachine类:
```java
public class CoffeeMachine {
private int coffeeCount; // 咖啡库存数量
private double balance; // 咖啡机余额
public CoffeeMachine(int coffeeCount, double balance) {
this.coffeeCount = coffeeCount;
this.balance = balance;
}
public int getCoffeeCount() {
return coffeeCount;
}
public void setCoffeeCount(int coffeeCount) {
this.coffeeCount = coffeeCount;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
// 咖啡售卖方法
public void sellCoffee(Customer customer) {
if (coffeeCount <= 0) {
System.out.println("咖啡机已售罄!");
return;
}
if (customer.getBalance() < 10) {
System.out.println("余额不足,请先充值!");
return;
}
coffeeCount--;
balance += 10;
customer.setBalance(customer.getBalance() - 10);
System.out.println("咖啡售出成功!");
}
}
```
Coffee类:
```java
public class Coffee {
private String name; // 咖啡名称
private double price; // 咖啡价格
public Coffee(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
```
Customer类:
```java
public class Customer {
private double balance; // 余额
public Customer(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
```
这三个类分别表示咖啡售卖机、咖啡和顾客。其中,Coffee类只是一个简单的咖啡类,用于存储咖啡的名称和价格。Customer类表示顾客,只有一个余额属性。CoffeeMachine类是咖啡售卖机,拥有咖啡库存数量和余额属性,以及售卖咖啡的方法sellCoffee()。在该方法中,首先判断咖啡库存数量是否大于0,如果不是,则提示“咖啡机已售罄!”;然后判断顾客的余额是否足够购买咖啡,如果不足,则提示“余额不足,请先充值!”;否则,咖啡库存数量减1,咖啡机余额加上咖啡价格,顾客余额减去咖啡价格,最后提示“咖啡售出成功!”。
下面是一个简单的测试代码:
```java
public class Test {
public static void main(String[] args) {
CoffeeMachine coffeeMachine = new CoffeeMachine(10, 0);
Customer customer = new Customer(20);
Coffee coffee = new Coffee("拿铁", 10);
coffeeMachine.sellCoffee(customer);
System.out.println("余额:" + customer.getBalance() + ",咖啡机余额:" + coffeeMachine.getBalance() + ",咖啡库存:" + coffeeMachine.getCoffeeCount());
coffeeMachine.sellCoffee(customer);
System.out.println("余额:" + customer.getBalance() + ",咖啡机余额:" + coffeeMachine.getBalance() + ",咖啡库存:" + coffeeMachine.getCoffeeCount());
customer.setBalance(5);
coffeeMachine.sellCoffee(customer);
System.out.println("余额:" + customer.getBalance() + ",咖啡机余额:" + coffeeMachine.getBalance() + ",咖啡库存:" + coffeeMachine.getCoffeeCount());
}
}
```
该测试代码创建了一个咖啡售卖机对象、一个顾客对象和一个咖啡对象。第一次售卖咖啡时,因为顾客余额足够且咖啡库存充足,所以售卖成功;第二次售卖咖啡时,由于咖啡库存不足,所以售卖失败;第三次售卖咖啡时,由于顾客余额不足,所以售卖失败。最后,打印出顾客余额、咖啡机余额和咖啡库存的信息。