62,620
社区成员
发帖
与我相关
我的任务
分享
package candyMachine;
public class Dispenser
{
private int numberOfltems;
private int cost;
public Dispenser()
{ numberOfltems = 50;
cost = 50;
}
public Dispenser( int setNoOfltems, int setCost )
{ if( setNoOfltems >= 0 )
numberOfltems = setNoOfltems;
else
numberOfltems = 50;
if( setCost >= 0 )
cost = setCost;
else
cost = 50;
}
public int getCount()
{ return numberOfltems;
}
public int getProductCost()
{ return cost;
}
public void makeSale()
{ numberOfltems --;
}
}
package candyMachine;
public class CashRegister
{private int cashOnHand;
public CashRegister( int cashIn )
{if(cashIn >= 0)
cashOnHand = cashIn;
else
cashOnHand = 500;
}
public CashRegister()
{cashOnHand = 500;
}
public int currentBalance()
{return cashOnHand;
}
public void acceptAmount( int amountIn )
{cashOnHand = cashOnHand + amountIn;
}
}
import java.io.* ;
import candyMachine.* ;
public class CandyMachine
{ static BufferedReader keyboard = new BufferedReader( new InputStreamReader( System.in ) );
public static void main( String[] args ) throws IOException
{
CashRegister cashRegister = new CashRegister();
Dispenser andy = new Dispenser(100, 50 );
Dispenser chips = new Dispenser( 100,65 );
Dispenser gum = new Dispenser( 75,45 );
Dispenser cookies = new Dispenser( 100,85 );
int choice;
showSelection();
choice = Integer.parseInt( keyboard.readLine() );
while( choice != 9 )
{ switch( choice )
{ 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 " );
}
showSelection();
choice = Integer.parseInt( keyboard.readLine() );
}
}
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 Chip" );
System.out.println( "3 for Gum " );
System.out.println( "4 for Cookies" );
System.out.println( "9 to exit");
}
public static void sellProduct( Dispenser product, CashRegister cRegister ) throws IOException
{ int amount;
int amount2;
if( product.getCount() > 0 )
{ 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" );
}
}