SlideShare a Scribd company logo
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

More Related Content

PDF
For this homework, you will develop a class called VendingMachine th.pdf
PDF
This is a java lab assignment. I have added the first part java re.pdf
PDF
BELOW IS MY CODE FOR THIS ASSIGMENT BUT IT NOT WORKING WELL PLEASE H.pdf
PDF
I have the source code for three separate java programs (TestVending.pdf
PDF
import java.util.Random;defines the Stock class public class S.pdf
PDF
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
DOCX
--Book-java package bookStore- public class Book extends Product { (1).docx
PDF
Develop an inventory management system for an electronics store. The .pdf
For this homework, you will develop a class called VendingMachine th.pdf
This is a java lab assignment. I have added the first part java re.pdf
BELOW IS MY CODE FOR THIS ASSIGMENT BUT IT NOT WORKING WELL PLEASE H.pdf
I have the source code for three separate java programs (TestVending.pdf
import java.util.Random;defines the Stock class public class S.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
--Book-java package bookStore- public class Book extends Product { (1).docx
Develop an inventory management system for an electronics store. The .pdf

Similar to Write a program that mimics the operations of several vending machin.pdf (20)

PDF
ARabia hossain project report.pdf
PDF
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
PDF
Begin with the InventoryItem class and InventoryDemo fronte.pdf
PDF
Java Programming Projects
DOCX
I received answers to 2 App requests and paid. The JAVA Apps are not.docx
TXT
Code
PDF
MenuItemvpublic class MenuItem .pdf
DOCX
Automated Restaurant System (Command Design Pattern)PROBLEMY.docx
DOCX
computer project on shopping mall..cbse 2017-2018 project
PDF
Vending-machine.pdf
PDF
Inventory Management System objective Work with multiple objects and.pdf
DOCX
You are to write a program that computes customers bill for hisher.docx
PDF
This application is used to keep track of inventory information. A c.pdf
PDF
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
PPTX
Computer Programming Code Sample
DOCX
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
PDF
show code and all classes with full implementation for these Program S.pdf
PDF
So I already have most of the code and now I have to1. create an .pdf
DOCX
import java.util.ArrayList;public class Checkout{private.docx
PPTX
Coffee ordering system using java cosole
ARabia hossain project report.pdf
database propertiesjdbc.url=jdbcderbyBigJavaDB;create=true # .pdf
Begin with the InventoryItem class and InventoryDemo fronte.pdf
Java Programming Projects
I received answers to 2 App requests and paid. The JAVA Apps are not.docx
Code
MenuItemvpublic class MenuItem .pdf
Automated Restaurant System (Command Design Pattern)PROBLEMY.docx
computer project on shopping mall..cbse 2017-2018 project
Vending-machine.pdf
Inventory Management System objective Work with multiple objects and.pdf
You are to write a program that computes customers bill for hisher.docx
This application is used to keep track of inventory information. A c.pdf
Hello. I need help fixing this Java Code on Eclipse. Please fix part.pdf
Computer Programming Code Sample
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
show code and all classes with full implementation for these Program S.pdf
So I already have most of the code and now I have to1. create an .pdf
import java.util.ArrayList;public class Checkout{private.docx
Coffee ordering system using java cosole
Ad

More from eyebolloptics (20)

PDF
How does law enforcement, courts and corrections work to complemen.pdf
PDF
Check all that apply to different sets of genes that are homologous..pdf
PDF
For the following matrices, determine a cot of basis vectors for the.pdf
PDF
Exploring Organizational Culture Research the ITT Tech Virtual Lib.pdf
PDF
Can you help me write these functions in C I do not need the main f.pdf
PDF
Drag the term or statement to the correct column SolutionC.pdf
PDF
Define the labor relations processSolutionThe labor relations.pdf
PDF
Accounting 5205Solution Depreciation aims to recognize in the.pdf
PDF
Aiom for the ADT List. C++ Explain what this pseudocode is doing.a.pdf
PDF
an encryption scheme distributes randomly over the Ascii characters .pdf
PDF
A class has 40 students aged 17 to 34. What is the probabilty that a.pdf
PDF
A microbial geneticist isolates a new mutation in E. coli and wishes.pdf
PDF
30. The vouching of recorded payables to supporting documentation wil.pdf
PDF
3. Observe that every cation was initially part of a nitrate compound.pdf
PDF
1)Please explain the commands ifconfig, ping, traceroute, netstat, d.pdf
PDF
At what point does commercialization start to create inequality Ple.pdf
PDF
A benefit of an activity received by people not participating in the.pdf
PDF
You are given a specification for some Java classes as follows.  A.pdf
PDF
8. Would the following cell have a spontaneous reaction Explain. .pdf
PDF
Write a command to find out how many users in etcpasswd have the l.pdf
How does law enforcement, courts and corrections work to complemen.pdf
Check all that apply to different sets of genes that are homologous..pdf
For the following matrices, determine a cot of basis vectors for the.pdf
Exploring Organizational Culture Research the ITT Tech Virtual Lib.pdf
Can you help me write these functions in C I do not need the main f.pdf
Drag the term or statement to the correct column SolutionC.pdf
Define the labor relations processSolutionThe labor relations.pdf
Accounting 5205Solution Depreciation aims to recognize in the.pdf
Aiom for the ADT List. C++ Explain what this pseudocode is doing.a.pdf
an encryption scheme distributes randomly over the Ascii characters .pdf
A class has 40 students aged 17 to 34. What is the probabilty that a.pdf
A microbial geneticist isolates a new mutation in E. coli and wishes.pdf
30. The vouching of recorded payables to supporting documentation wil.pdf
3. Observe that every cation was initially part of a nitrate compound.pdf
1)Please explain the commands ifconfig, ping, traceroute, netstat, d.pdf
At what point does commercialization start to create inequality Ple.pdf
A benefit of an activity received by people not participating in the.pdf
You are given a specification for some Java classes as follows.  A.pdf
8. Would the following cell have a spontaneous reaction Explain. .pdf
Write a command to find out how many users in etcpasswd have the l.pdf
Ad

Recently uploaded (20)

PDF
Anesthesia in Laparoscopic Surgery in India
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Cell Types and Its function , kingdom of life
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Institutional Correction lecture only . . .
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
Anesthesia in Laparoscopic Surgery in India
2.FourierTransform-ShortQuestionswithAnswers.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Final Presentation General Medicine 03-08-2024.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Complications of Minimal Access Surgery at WLH
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Chinmaya Tiranga quiz Grand Finale.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
O7-L3 Supply Chain Operations - ICLT Program
Abdominal Access Techniques with Prof. Dr. R K Mishra
Cell Types and Its function , kingdom of life
O5-L3 Freight Transport Ops (International) V1.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Institutional Correction lecture only . . .
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
202450812 BayCHI UCSC-SV 20250812 v17.pptx
VCE English Exam - Section C Student Revision Booklet

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

  • 1. 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
  • 2. 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
  • 3. */ 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;
  • 4. } /* * (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 + "]"; }
  • 5. } --------------- 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;
  • 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 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
  • 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 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()) {
  • 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 user balance46.0 1 drinks 2 snacks 3 quit enter your choice 3 do you want to exit if yes press 'x' x