自动售货机
实现基本的自动售货机的功能,包括商品种类显示,商品价格显示,商品余量显示,找零显示等
Java 代码
package machine;
import java.util.Scanner;
public class VendingMachine {
int drinkNumber;
int total = 0;//总共收到的钱
int amount = 0;//顾客投入的钱
String[] drink = {"1:苹果汁 ","2:可乐 ","3:牛奶 ","4:橙汁 "," 5:苏打水"};//饮品种类
int[] price = {5,3,6,4,2};//饮品价格
int[] quantity = {3,3,3,3,3};//所剩饮品数量
Scanner in = new Scanner(System.in);
void showPrompt() {
System.out.println("欢迎!");
}
void initDrink() {
int i;
System.out.printf("饮品种类:");
for ( i=0 ; i<drink.length ; i++) {
System.out.printf("%s",drink[i]);
}
if (i == drink.length) {
System.out.printf("\n");
}
}
void chooseDrink() {
System.out.println("请输入要购买饮品序号");
this.drinkNumber = this.in.nextInt()-1;
}
void insertMony() {
System.out.println("请将纸币插入钞票口");
this.amount = this.in.nextInt();
}
void getDrink() {
int price;
price = this.price[drinkNumber];
if(quantity[drinkNumber]>0) {
if (amount > price) {
System.out.printf("找您%d元\n",(amount - price));
System.out.printf("这是您要的%s,慢走不送\n",drink[drinkNumber]);
this.total = amount - price + this.total;
this.quantity[drinkNumber]--;
}else if(amount == price) {
System.out.printf("这是您要的%s,慢走不送\n",drink[drinkNumber]);
this.total += amount;
this.quantity[drinkNumber]--;
}else {
System.out.printf("余额不够,退您%d元",amount);
}
}else {
System.out.println("对不起,商品缺货");
}
}
public static void main(String[] args) {
VendingMachine m1 = new VendingMachine();
while(true) {
m1.showPrompt();
m1.initDrink();
m1.chooseDrink();
m1.insertMony();
m1.getDrink();
}
}
}