1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
| 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();
}
}
}
|