📄 candymachine.java
字号:
// Program candy machine
import java.io.*;
public class CandyMachine
{
static BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException
{
CashRegister cashRegister = new CashRegister(); //Step 1
Dispenser candy = new Dispenser(100,50); //Step 2
Dispenser chips = new Dispenser(100,65); //Step 2
Dispenser gum = new Dispenser(75,45); //Step 2
Dispenser cookies = new Dispenser(100,85); //Step 2
int choice; //variable to hold the selection //Step 3
showSelection(); //Step 4
choice = Integer.parseInt(keyboard.readLine()); //Step 5
while(choice != 9) //Step 6
{
switch(choice) //Step 6a
{
case 1: sellProduct(candy, cashRegister);
break;
case 2: sellProduct(chips, cashRegister);
break;
case 3: sellProduct(gum, cashRegister);
break;
case 4: sellProduct(cookies, cashRegister);
break;
default: System.out.println("Invalid Selection");
}//end switch
showSelection(); //Step 6b
choice = Integer.parseInt(keyboard.readLine()); //Step 6c
}//end while
}//end main
public static void showSelection()
{
System.out.println("*** Welcome to Shelly's Candy Shop ***");
System.out.println("To select an item, enter ");
System.out.println("1 for Candy");
System.out.println("2 for Chips");
System.out.println("3 for Gum");
System.out.println("4 for Cookies");
System.out.println("9 to exit");
}//end showSelection
public static void sellProduct(Dispenser product,
CashRegister cRegister)
throws IOException
{
int amount; //variable to hold the amount entered
int amount2; //variable to hold the extra amount needed
if(product.getCount() > 0) //if dispenser is not empty
{
System.out.println("Please deposit "
+ product.getProductCost()
+ " cents");
amount = Integer.parseInt(keyboard.readLine());
if(amount < product.getProductCost())
{
System.out.println("Please deposit another "
+ (product.getProductCost() - amount)
+ " cents");
amount2 = Integer.parseInt(keyboard.readLine());
amount = amount + amount2;
}
if(amount >= product.getProductCost())
{
cRegister.acceptAmount(amount);
product.makeSale();
System.out.println("Collect your item at the "
+ "bottom and enjoy.");
}
else
System.out.println("The amount is not enough. "
+ "Collect what you deposited.");
System.out.println("*-*-*-*-*-*-*-*-*-*-"
+ "*-*-*-*-*-*-*-*-*-*");
}
else
System.out.println("Sorry this item is sold out.");
}//end sellProduct
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -