Write a program that mimics the operations of several vending machines. More specifically, the
program simulates what happens when the user chooses one of the vending machines, inputs
money and picks an item from the vending machine. Assume there are two vending machines:
one for drinks and one for snacks. Each vending machine contains several items. The name,
price, and quantity of each item is given in two text files; one named “drinks.txt” for the drinks
vending machine and the other named “snacks.txt” for the snacks vending machine.
The format of the input values is comma-separated. The items listed should be organized in the
file with the following order: name, price, quantity. Here are some example items:
The actual reading and parsing of the input file is already handled in the class supplied to you
(see code on BlackBoard). You are given the variables as individual values. You will need to
create the .txt files for creating and testing your vending machines.
You will need to create/complete three classes for this homework assignment: Item,
VendingMachine, and VendingMachineDriver.
Problem Description
Milk,2.00,1
Within your VendingMachine class, include these methods:
VendingMachineThisconstructormethodwilltakeinthenameoftheinputfileand create a vending
machine object. A vending machine object will contain an array of Item objects called stock and
an amount of revenue earned. This constructor method has been completed for you and should
work appropriately once you have completed the rest of this class and the other class definitions.
vendThismethodwillsimulatethevendingtransactionafteravalidamountofmoney and an item
selection are entered. This method will decide if the transaction is successful (enough money or
item) and update the vending machine appropriately.
outputMessage This method will print an appropriate message depending on the success of the
transaction. If the user does not have enough money to buy the chosen item, the vending machine
should prompt the user to enter more money or exit the machine. If the vending machine is out of
the chosen item, the program will print an apology message and prompt the user to choose
another item or exit the machine. If there is enough money for the item selected, then the
vending machine will give the user the item and return the change.
printMenuThismethodprintsthemenuofitemsforthechosenvendingmachine. The Item class needs
to include the following data variables:
• description as a String
• price as a double
• quantity as an int
Within your VendingMachineDriver class, include a main method as the starting point for your
solution that creates the vending machine objects appropriately and then use a loop that
continues interacting with the vending machines until the user enters “X” to exit. See the sample
session for details.
As you implement your solution, you might find that some methods contain some repeated
coding logic. To avoid unnecessary redundancies in your code, have these methods call an
appropriate helper method.
Solution
package com.gp.classes;
public class Item {
protected String itemDesc;
protected double price;
protected int quantity;
/**
* @return the itemDesc
*/
public String getItemDesc() {
return itemDesc;
}
/**
* @param itemDesc
* the itemDesc to set
*/
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price
* the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* @return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* @param quantity
* the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Item(String itemDesc, double price, int quantity) {
this.itemDesc = itemDesc;
this.price = price;
this.quantity = quantity;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((itemDesc == null) ? 0 : itemDesc.hashCode());
result = (int) (prime * result + price);
result = prime * result + quantity;
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item other = (Item) obj;
if (itemDesc == null) {
if (other.itemDesc != null)
return false;
} else if (!itemDesc.equals(other.itemDesc))
return false;
if (price != other.price)
return false;
if (quantity != other.quantity)
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Item [itemDesc=" + itemDesc + ", price=" + price
+ ", quantity=" + quantity + "]";
}
}
---------------
package com.gp.classes;
public class User {
private double money;
public User(double money) {
this.money = money;
}
/**
* @return the money
*/
public double getMoney() {
return money;
}
/**
* @param money
* the money to set
*/
public void setMoney(double money) {
this.money = money;
}
}
-----------------------------------------------------------------------------------
package com.gp.classes;
public class Drink extends Item {
public String itemDesc;
public double price;
public int quantity;
public Drink(String itemDesc, double price, int quantity) {
super(itemDesc, price, quantity);
}
/**
* @return the itemDesc
*/
public String getItemDesc() {
return itemDesc;
}
/**
* @param itemDesc
* the itemDesc to set
*/
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price
* the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* @return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* @param quantity
* the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
------------------------------------------------------------------------------------
package com.gp.classes;
public class Snacks extends Item {
public String itemDesc;
public double price;
public int quantity;
public Snacks(String itemDesc, double price, int quantity) {
super(itemDesc, price, quantity);
}
/**
* @return the itemDesc
*/
public String getItemDesc() {
return itemDesc;
}
/**
* @param itemDesc
* the itemDesc to set
*/
public void setItemDesc(String itemDesc) {
this.itemDesc = itemDesc;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price
* the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* @return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* @param quantity
* the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
------------------------------------------------------
package com.gp.classes;
import java.io.*;
import java.util.Scanner;
/*************************************************************************
* Simulates a real life vending machine with stock read from a file.
*
* CSCE 155A Fall 2016 Assignment 4
*
* @file VendingMachine.java
* @author Jeremy Suing
* @version 1.0
* @date March 7, 2016
*************************************************************************/
public class VendingMachine {
// data members
public User user = new User(56.0);
public double usermoney = user.getMoney();
private Item[] stock; // Array of Item objects in machine
private double money; // Amount of revenue earned by machine
public VendingMachineDriver driver = new VendingMachineDriver();
static Scanner scanner1 = new Scanner(System.in);
/*********************************************************************
* This is the constructor of the VendingMachine class that take a file name
* for the items to be loaded into the vending machine.
*
* It creates objects of the Item class from the information in the file to
* populate into the stock of the vending machine. It does this by looping
* the file to determine the number of items and then reading the items and
* populating the array of stock.
*
* @param filename
* Name of the file containing the items to stock into this
* instance of the vending machine.
* @throws FileNotFoundException
* If issues reading the file.
*********************************************************************/
public VendingMachine(String filename) throws FileNotFoundException {
// Open the file to read with the scanner
File file = new File(filename);
Scanner scan = new Scanner(file);
// Determine the total number of items listed in the file
int totalItem = 0;
while (scan.hasNextLine()) {
scan.nextLine();
totalItem++;
} // End while another item in file
// Create the array of stock with the appropriate number of items
stock = new Item[totalItem];
scan.close();
// Open the file again with a new scanner to read the items
scan = new Scanner(file);
int itemQuantity = -1;
double itemPrice = -1;
String itemDesc = "";
int count = 0;
String line = "";
// Read through the items in the file to get their information
// Create the item objects and put them into the array of stock
while (scan.hasNextLine()) {
line = scan.nextLine();
String[] tokens = line.split(",");
try {
itemDesc = tokens[0];
itemPrice = Double.parseDouble(tokens[1]);
itemQuantity = Integer.parseInt(tokens[2]);
stock[count] = new Item(itemDesc, itemPrice, itemQuantity);
count++;
} catch (NumberFormatException nfe) {
System.out.println("Bad item in file " + filename + " on row "
+ (count + 1) + ".");
}
} // End while another item in file
scan.close();
// Initialize the money data variable.
money = 0.0;
} // End VendingMachine constructor
public void vend() throws Exception {
int count = 0;
String[] names = new String[stock.length];
for (Item item : stock) {
System.out.println(item);
String name = item.itemDesc;
names[count] = name;
System.out.println("the items are :" + names[count]);
count++;
}
System.out.println("enter your required item");
String useritem = scanner1.next();
for (int k = 0; k < names.length; k++) {
// System.out.println("the names are"+names[i]);
if (useritem.trim().equals(names[k])) {
for (Item item1 : stock) {
if (useritem.trim().equals(item1.itemDesc)) {
if (usermoney > item1.price) {
usermoney = usermoney - item1.price;
user.setMoney(usermoney);
money = money + item1.price;
outputmessage();
} else
System.out.println("insufficient funds");
}
}
}// end if
}// end for
}// end of the method
public void outputmessage() {
System.out.println("transaction is success");
printMenu();
}
public void printMenu() {
System.out.println("the vending machine income" + money);
System.out.println("the remaining user balance" + user.getMoney());
}
}// end of the class
------------------------------------------------------------
package com.gp.classes;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class VendingMachineDriver {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.out.println(" 1 drinks");
System.out.println("2 snacks");
System.out.println("3 quit");
System.out.println("enter your choice");
System.out.println("");
int choice = scanner.nextInt();
switch (choice) {
case 1:
VendingMachine vending = new VendingMachine("D:drinks.txt");
vending.vend();
main(args);
break;
case 2:
VendingMachine vending1 = new VendingMachine("D:snacks.txt");
vending1.vend();
main(args);
break;
case 3:
System.out
.println(" do you want to exit if yes press 'x' else type anything");
String character = scanner.next();
if (character.trim().equals("x")) {
System.exit(0);
} else
main(null);
default:
System.out.println("bad choice");
break;
}
}
}
output
1 drinks
2 snacks
3 quit
enter your choice
1
Item [itemDesc=cocacola, price=10.0, quantity=4]
the items are :cocacola
Item [itemDesc=pepsi, price=2.5, quantity=5]
the items are :pepsi
enter your required item
cocacola
transaction is success
the vending machine income10.0
the remaining user balance46.0
1 drinks
2 snacks
3 quit
enter your choice
3
do you want to exit if yes press 'x'
x

Write a program that mimics the operations of several vending machin.pdf

  • 1.
    Write a programthat mimics the operations of several vending machines. More specifically, the program simulates what happens when the user chooses one of the vending machines, inputs money and picks an item from the vending machine. Assume there are two vending machines: one for drinks and one for snacks. Each vending machine contains several items. The name, price, and quantity of each item is given in two text files; one named “drinks.txt” for the drinks vending machine and the other named “snacks.txt” for the snacks vending machine. The format of the input values is comma-separated. The items listed should be organized in the file with the following order: name, price, quantity. Here are some example items: The actual reading and parsing of the input file is already handled in the class supplied to you (see code on BlackBoard). You are given the variables as individual values. You will need to create the .txt files for creating and testing your vending machines. You will need to create/complete three classes for this homework assignment: Item, VendingMachine, and VendingMachineDriver. Problem Description Milk,2.00,1 Within your VendingMachine class, include these methods: VendingMachineThisconstructormethodwilltakeinthenameoftheinputfileand create a vending machine object. A vending machine object will contain an array of Item objects called stock and an amount of revenue earned. This constructor method has been completed for you and should work appropriately once you have completed the rest of this class and the other class definitions. vendThismethodwillsimulatethevendingtransactionafteravalidamountofmoney and an item selection are entered. This method will decide if the transaction is successful (enough money or item) and update the vending machine appropriately. outputMessage This method will print an appropriate message depending on the success of the transaction. If the user does not have enough money to buy the chosen item, the vending machine should prompt the user to enter more money or exit the machine. If the vending machine is out of the chosen item, the program will print an apology message and prompt the user to choose another item or exit the machine. If there is enough money for the item selected, then the vending machine will give the user the item and return the change. printMenuThismethodprintsthemenuofitemsforthechosenvendingmachine. The Item class needs to include the following data variables: • description as a String • price as a double • quantity as an int Within your VendingMachineDriver class, include a main method as the starting point for your
  • 2.
    solution that createsthe vending machine objects appropriately and then use a loop that continues interacting with the vending machines until the user enters “X” to exit. See the sample session for details. As you implement your solution, you might find that some methods contain some repeated coding logic. To avoid unnecessary redundancies in your code, have these methods call an appropriate helper method. Solution package com.gp.classes; public class Item { protected String itemDesc; protected double price; protected int quantity; /** * @return the itemDesc */ public String getItemDesc() { return itemDesc; } /** * @param itemDesc * the itemDesc to set */ public void setItemDesc(String itemDesc) { this.itemDesc = itemDesc; } /** * @return the price */ public double getPrice() { return price; } /** * @param price * the price to set
  • 3.
    */ public void setPrice(doubleprice) { this.price = price; } /** * @return the quantity */ public int getQuantity() { return quantity; } /** * @param quantity * the quantity to set */ public void setQuantity(int quantity) { this.quantity = quantity; } public Item(String itemDesc, double price, int quantity) { this.itemDesc = itemDesc; this.price = price; this.quantity = quantity; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((itemDesc == null) ? 0 : itemDesc.hashCode()); result = (int) (prime * result + price); result = prime * result + quantity; return result;
  • 4.
    } /* * (non-Javadoc) * * @seejava.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Item other = (Item) obj; if (itemDesc == null) { if (other.itemDesc != null) return false; } else if (!itemDesc.equals(other.itemDesc)) return false; if (price != other.price) return false; if (quantity != other.quantity) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Item [itemDesc=" + itemDesc + ", price=" + price + ", quantity=" + quantity + "]"; }
  • 5.
    } --------------- package com.gp.classes; public classUser { private double money; public User(double money) { this.money = money; } /** * @return the money */ public double getMoney() { return money; } /** * @param money * the money to set */ public void setMoney(double money) { this.money = money; } } ----------------------------------------------------------------------------------- package com.gp.classes; public class Drink extends Item { public String itemDesc; public double price; public int quantity; public Drink(String itemDesc, double price, int quantity) { super(itemDesc, price, quantity); } /** * @return the itemDesc */ public String getItemDesc() { return itemDesc;
  • 6.
    } /** * @param itemDesc *the itemDesc to set */ public void setItemDesc(String itemDesc) { this.itemDesc = itemDesc; } /** * @return the price */ public double getPrice() { return price; } /** * @param price * the price to set */ public void setPrice(double price) { this.price = price; } /** * @return the quantity */ public int getQuantity() { return quantity; } /** * @param quantity * the quantity to set */ public void setQuantity(int quantity) { this.quantity = quantity; } } ------------------------------------------------------------------------------------
  • 7.
    package com.gp.classes; public classSnacks extends Item { public String itemDesc; public double price; public int quantity; public Snacks(String itemDesc, double price, int quantity) { super(itemDesc, price, quantity); } /** * @return the itemDesc */ public String getItemDesc() { return itemDesc; } /** * @param itemDesc * the itemDesc to set */ public void setItemDesc(String itemDesc) { this.itemDesc = itemDesc; } /** * @return the price */ public double getPrice() { return price; } /** * @param price * the price to set */ public void setPrice(double price) { this.price = price; } /** * @return the quantity
  • 8.
    */ public int getQuantity(){ return quantity; } /** * @param quantity * the quantity to set */ public void setQuantity(int quantity) { this.quantity = quantity; } } ------------------------------------------------------ package com.gp.classes; import java.io.*; import java.util.Scanner; /************************************************************************* * Simulates a real life vending machine with stock read from a file. * * CSCE 155A Fall 2016 Assignment 4 * * @file VendingMachine.java * @author Jeremy Suing * @version 1.0 * @date March 7, 2016 *************************************************************************/ public class VendingMachine { // data members public User user = new User(56.0); public double usermoney = user.getMoney(); private Item[] stock; // Array of Item objects in machine private double money; // Amount of revenue earned by machine public VendingMachineDriver driver = new VendingMachineDriver(); static Scanner scanner1 = new Scanner(System.in); /********************************************************************* * This is the constructor of the VendingMachine class that take a file name
  • 9.
    * for theitems to be loaded into the vending machine. * * It creates objects of the Item class from the information in the file to * populate into the stock of the vending machine. It does this by looping * the file to determine the number of items and then reading the items and * populating the array of stock. * * @param filename * Name of the file containing the items to stock into this * instance of the vending machine. * @throws FileNotFoundException * If issues reading the file. *********************************************************************/ public VendingMachine(String filename) throws FileNotFoundException { // Open the file to read with the scanner File file = new File(filename); Scanner scan = new Scanner(file); // Determine the total number of items listed in the file int totalItem = 0; while (scan.hasNextLine()) { scan.nextLine(); totalItem++; } // End while another item in file // Create the array of stock with the appropriate number of items stock = new Item[totalItem]; scan.close(); // Open the file again with a new scanner to read the items scan = new Scanner(file); int itemQuantity = -1; double itemPrice = -1; String itemDesc = ""; int count = 0; String line = ""; // Read through the items in the file to get their information // Create the item objects and put them into the array of stock while (scan.hasNextLine()) {
  • 10.
    line = scan.nextLine(); String[]tokens = line.split(","); try { itemDesc = tokens[0]; itemPrice = Double.parseDouble(tokens[1]); itemQuantity = Integer.parseInt(tokens[2]); stock[count] = new Item(itemDesc, itemPrice, itemQuantity); count++; } catch (NumberFormatException nfe) { System.out.println("Bad item in file " + filename + " on row " + (count + 1) + "."); } } // End while another item in file scan.close(); // Initialize the money data variable. money = 0.0; } // End VendingMachine constructor public void vend() throws Exception { int count = 0; String[] names = new String[stock.length]; for (Item item : stock) { System.out.println(item); String name = item.itemDesc; names[count] = name; System.out.println("the items are :" + names[count]); count++; } System.out.println("enter your required item"); String useritem = scanner1.next(); for (int k = 0; k < names.length; k++) { // System.out.println("the names are"+names[i]); if (useritem.trim().equals(names[k])) { for (Item item1 : stock) { if (useritem.trim().equals(item1.itemDesc)) { if (usermoney > item1.price) { usermoney = usermoney - item1.price;
  • 11.
    user.setMoney(usermoney); money = money+ item1.price; outputmessage(); } else System.out.println("insufficient funds"); } } }// end if }// end for }// end of the method public void outputmessage() { System.out.println("transaction is success"); printMenu(); } public void printMenu() { System.out.println("the vending machine income" + money); System.out.println("the remaining user balance" + user.getMoney()); } }// end of the class ------------------------------------------------------------ package com.gp.classes; import java.io.FileNotFoundException; import java.util.Scanner; public class VendingMachineDriver { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws Exception { // TODO Auto-generated method stub System.out.println(" 1 drinks"); System.out.println("2 snacks"); System.out.println("3 quit"); System.out.println("enter your choice"); System.out.println(""); int choice = scanner.nextInt(); switch (choice) { case 1: VendingMachine vending = new VendingMachine("D:drinks.txt");
  • 12.
    vending.vend(); main(args); break; case 2: VendingMachine vending1= new VendingMachine("D:snacks.txt"); vending1.vend(); main(args); break; case 3: System.out .println(" do you want to exit if yes press 'x' else type anything"); String character = scanner.next(); if (character.trim().equals("x")) { System.exit(0); } else main(null); default: System.out.println("bad choice"); break; } } } output 1 drinks 2 snacks 3 quit enter your choice 1 Item [itemDesc=cocacola, price=10.0, quantity=4] the items are :cocacola Item [itemDesc=pepsi, price=2.5, quantity=5] the items are :pepsi enter your required item cocacola transaction is success the vending machine income10.0
  • 13.
    the remaining userbalance46.0 1 drinks 2 snacks 3 quit enter your choice 3 do you want to exit if yes press 'x' x