用java写一个程序。用对象模拟实现一个售货过程。
时间: 2023-06-16 12:08:16 浏览: 76
Java实现 自动贩卖/售货机 系统
5星 · 资源好评率100%
好的,下面是一个简单的示例程序,模拟一个售货过程:
```java
import java.util.ArrayList;
public class VendingMachine {
private ArrayList<Product> products;
private float balance;
public VendingMachine() {
products = new ArrayList<>();
balance = 0;
}
public void addProduct(Product product) {
products.add(product);
}
public void insertCoin(float amount) {
balance += amount;
}
public void purchase(int productIndex) {
Product product = products.get(productIndex);
if (balance >= product.getPrice()) {
System.out.println("Dispensing " + product.getName());
balance -= product.getPrice();
} else {
System.out.println("Not enough balance");
}
}
public void displayProducts() {
for (int i = 0; i < products.size(); i++) {
Product product = products.get(i);
System.out.println(i + ": " + product.getName() + " - " + product.getPrice());
}
}
public float getBalance() {
return balance;
}
}
public class Product {
private String name;
private float price;
public Product(String name, float price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public float getPrice() {
return price;
}
}
public class Main {
public static void main(String[] args) {
VendingMachine vendingMachine = new VendingMachine();
vendingMachine.addProduct(new Product("Coke", 1.5f));
vendingMachine.addProduct(new Product("Chips", 2.0f));
vendingMachine.addProduct(new Product("Candy", 0.5f));
vendingMachine.displayProducts();
vendingMachine.insertCoin(1.0f);
vendingMachine.purchase(0);
vendingMachine.insertCoin(2.0f);
vendingMachine.purchase(1);
vendingMachine.insertCoin(1.0f);
vendingMachine.purchase(2);
}
}
```
程序中有三个类:VendingMachine、Product和Main。
VendingMachine类表示售货机,里面有一个产品列表和一个余额变量。其中,addProduct方法用于添加产品,insertCoin方法用于插入硬币,purchase方法用于购买产品,displayProducts方法用于显示产品列表,getBalance方法用于获取余额。
Product类表示产品,包含名称和价格两个属性。
Main类是程序的入口,创建一个VendingMachine对象并添加三个产品,然后插入硬币、购买产品并显示余额。
阅读全文