Your task in this assignment is to write a simple class definition for a vending
ID: 3691780 • Letter: Y
Question
Your task in this assignment is to write a simple class definition for a vending machine in Java. The class should have:
Attributes Soda count Money credit (how much money has been inserted)
Methods Add money Vend Restock Constructor
For simplicity sake, you may assume that the machine can hold up to 50 of one type of soda; you may also assume that all sodas cost $0.65. When adding money, simply take in a floating-point number representing how much money to add (i.e. you do not have to manage different coins).
Be sure to make sure that enough money was added to the machine before a soda is vended. Also, when a soda is vended, return the appropriate change (i.e. if more than $0.65 was added to the machine, then return the extra money). Again, don't worry about managing different kinds of coins – just display the amount returned.
When the machine is "restocked," just set the soda count to the maximum that the machine will hold.
Once you have written the class, create a main/driver program that interacts with an instance of the class. Your program should present a menu of options to the user and process the user's choice; use creativity and object-oriented design in your solution.
Explanation / Answer
public class VendingMachine
{
private final double SODA_COST=0.65;
privare final int MAX_SODAS=50;
private int sodaCount;
private double moneyCredit;
public VendingMachine()
{
sodaCount = MAX_SODAS;
moneyCredit = 0;
}
public void addMoney(double amount)
{
moneyCredit = amount;
}
public double vend()
{
if(moneyCredit < SODA_COST)
{
System.out.println("No enough money is in the machine to get soda.");
return 0;
}
if(sodaCount==0)
{
System.out.println("No enough money is in the machine to get soda.");
return 0;
}
sodaCount=sodaCount-1;
double change=moneyCredit-SODA_COST;
moneyCredit=0;
return change;
}
public void restock()
{
sodaCount=MAX_SODAS;
}
}
public class Assignment7_main
{
public static void main(String[]args)
{
VendingMachine machine=new VendingMachine();
Scanner input=new Scanner(System.in);
int choice;
double amount;
do
{
printMenu();
System.out.print("Enter your choice:");
choice=input.nextInt();
switch(choice)
{
case1:
System.out.print("Enter money to be added:$");
amount=input.nextDouble();
machine.addMoney(amount);
break;
case2:
amount=machine.vend();
System.out.printf("Returned amount:$%.2f ",amount);
break;
case3:
machine.restock();
break;
case 4:
System.out.println("Thank you");
break;
default:
System.out.prinln("Invalid choice");
}
System.out.println();
}
while(choice!=4);
}
public static void printMenu()
{
System.out.println("____MENU____");
System.out.println("1.Add money");
System.out.println("2.Vend");
System.out,println("3.Restock");
Sysyem.out.println("4.Exit");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.