Mock vending machine program that uses data from a file - java

I am working on a program that mimics a vending machine, it needs to pull data from a .txt file and use that information in the program. I want it to ask the user to input their amount of money and give them change as well. I want to store the prices in 2d arrays as well as the item names then have the user pick an item to buy. I am not sure how to go about this!! I really need some help, this is what I have so far.
Code:
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
public class Vending
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.print("Enter your food selection file: "); // User inputs file
Scanner input = new Scanner(System.in); // Keyboard input from user
Scanner fs = new Scanner(new File(input.nextLine())); // Scans in the file that was inputed
}
double price = 0;
while(fs.hasNextLine()){
fs.next();
price = fs.nextDouble();
System.out.print(price);
}
}
Item list file (Food.txt):
1        Honey roasted peanuts
1.50  Cheetos
1.50 Bugles
2        Synder’s Pretzels
1        Snickers
1        Twix
1.25 M n Ms
.75     Life savers
1        Twizzlers
1        Nutter Butters
1        Butter Fingers
1.50  King Size Kit Kats
1.25  Carrot sticks
.50     Juicy Fruit
.50     Spearmint Gum
.50     Five gum
3.50  Pepperoni
1.75  Cheez-Its
.25     Slim Jim
1.50  Lays Barbeque Chips

Here are some thoughts:
Instead of a 2-D array, create a simple Item
POJO that
holds the item's name and price.
Read in each line of the input file
and create one Item for each.
Store each of those in an array.
Rather than having the user input the precise name of the item they
want, emulate a real vending machine and assign each item a number.
E.g., iterate over the array and let each index represent the "item
number" and then print out the item price and name.
Now you can have your application's main function:
Read the file and create the array
Print out the options
Ask user to select an option
Ask user to provide money
"Return" the product (i.e. print "here's your item")
Calculate and "return" the change (i.e. print "here's your $x.xx back")
Here's a pseudocode for the change calculation using an Item object:
double calculateChange(Item item, double money) {
double price = item.getPrice();
// if assignment needs to handle "money < price", do so here
return money - price;
}

Related

Introducing an array to store scores in Java

The question I am working on is:
Write a program that:
asks the user how many exam scores there are (and verifies that the user entered a positive integer), prompt the user for each real-valued score, one by one (as shown below in Sample program behavior / output: box), Calculate and output the average of the scores and count and output how many scores are greater than the average (as shown below in Sample program behavior / output: box).
Sample program behavior / output:
How many exams scores do you have to enter? 5
Enter score #1: 95.0
Enter score #2: 92.0
Enter score #3: 68.0
Enter score #4: 72.0
Enter score #5: 70.0
The average score is: 79.4
There are 2 scores larger than the average.
This is my code:
import java.util.Scanner;
public class testee {
public static void main(String[] args) {
int examnum = -1;
Scanner scan = new Scanner (System.in);
while (examnum<0) {
System.out.println("How many exam scores do you have to enter?");
examnum = scan.nextInt( );
}
for (int i=1; i<=examnum; i++) {
System.out.println("Enter score #" + i + ": ");
for (int a=1; a<=i; a++) {
a = scan.nextInt();
}
}
}
}
What I did produces the following output however my problem is that I need to store the scores that are input to later compute an average so inside my for loop I would need to store the scores as an array but I do not know how to approach that.
First prompt looks good however there is one small problem.
Hint: What condition would you use for your while loop if you wanted to ensure that the value entered was not less than 1 since zero would be rather non-productive?
It's always nice to inform the User of any invalid entry.
To place items into an Array you need to declare that array and initialize it to the proper size:
int[] scoresArray = new int[examnum];
Think about this, where do you think this line of code should be placed?
Hint: You need to ensure that the required array size is already properly established.
Why use two for loops when you can use only one? What can the second (inner nested) for loop do that the outer for loop just simply can't do?
Hint: Nothing! "Enter score #" + (i+1) + ": ". Of course in this case i (within the initialization section) would need to start from 0 and always be less than examnum (within the termination section).
If you want to add an element to your array, where do you think would be a great place in your code to do that?
Hint: int score = scan.nextInt(); scoresArray[i] = score;.
Things to consider:
When scores are being entered, do you think the User entries should be validated? What if the User enters one or more (or all) alpha characters instead of digits in any of your prompts that require an Integer value? Do you end up getting an InputMismatchException? How would you handle such a thing?
Yes, you can nest while loops within a for loop and visa-versa.

Program getting stuck in while loop?

I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.
Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.

How to find the minimum price of the product from a list of subproducts

I am making a program where it takes a txt file as input, and find the best price of the list of products
for example,
teddy bear
painted glass eyeball,10.5,2,glass;paint
glass,5,0,
paint,4,0,
teddy bear,null,4,painted glass eyeball;tiny shirt;faux bear fur fabric;sewing thread
faux bear fur fabric,15,2,bear;yarn
bear,100,0,
yarn,2,0,
sewing thread,13,0,
tiny shirt,24,0,
in the following example, our target_product is teddy bear, and on line 5, it has a null (meaning, you won't be able to just buy the whole teddy bear), and the 4 is input_product_size which stands for the amount of products required to make the target_product, and the rest are the input_products
painted glass eyeball, in line 2, can be bought for $10.5 or can be made with 2 ingredients, glass, paint
glass can be bought for $5, and requires no other ingredients to make.
Paint can be bought for $4, and requires no other ingredients.
but since making the painted glass eyeball costs $9, and buying costs $10.5, we will make it instead of buying it.
tiny shirt can be bought for $24
faux bear fur fabric can be bought for $15, or can be made with 2 ingredients, bear, and yarn
bear can be bought for $100
yarn can be bought for $2
but since the total of bear and yarn is $102 which is larger than $15, we will just buy the fabric instead of making it.
sewing thread can be bought for $13
so the total output for teddy bear's minimum price should be
9+24+15+13=61
Another example would be making a sandwich
sandwich
mayonnaise,1,0,
sand,0,0,
bread,3,3,yeast;water;flour
flour,1,0,
water,1,0,
yeast,1,0,
sandwich,10,6,mayonnaise;sand;bread;mozzarella;bacon;salt
bacon,3,1,pig
pig,1000,0,
salt,1,2,sea salt;iodine
iodine,40,0,
sea salt,.5,0,
mozzarella,3,0,
we found that sandwich can be bought for $10, or can be made with 6 ingredients from this line
sandwich,10,6,mayonnaise;sand;bread;mozzarella;bacon;salt
mayo costs $1
sand costs $0
bread costs $3 or requires 3 ingredients to make: flour, water, and yeast
flour costs $1
water costs $1
and yeast costs $1
so both making the product and buying it won't make a difference
mozzarella costs $3
bacon costs $3, or requires 1 ingredient to make: pig
since pig costs $1000, we can just buy bacon for $3
salt costs $1 or requires 2 ingredients to make, sea salt and iodine
since the total of sea salt and iodine is $40.5, more than $1, we can buy sea salt.
the total of making this sandwich would cost
Mayo $1
Sand $0
Bread $3
Bacon $3
Mozarella $3
Salt $1
-------------
Total: $11
but since buying this sandwich only costs $10, we will have $10 as our output.
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class BestPrice {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("teddybear.txt"));
// BufferedReader in = new BufferedReader(reader);
String line, input_products = null;
// setting first line as our target product
String target_product = in.readLine();
int finalprice = 0, totalPrice = 0, input_product_size = 0;
while ((line = in.readLine()) != null) {
String[] words = line.split(",");
for (String word : words) {
if (word.equals(target_product)) {
if (words[1].equals("null")) {
// find the line where the target_product is,
// and parse it to get the rest of the information
String product_name = words[0];
String price_to_purchase = words[1];
input_product_size = Integer.parseInt(words[2]);
input_products = words[3];
if (input_product_size != 0) {
String[] ingredients = words[3].split(";");
for (int i = 0; i < ingredients.length; i++) {
if(word.equals(ingredients[i])) {}
}
}
// System.out.println(product_name + ", " + price_to_purchase + ", " +
// input_products);
} else {
// keep track of the cost of buying target_product
finalprice += Integer.parseInt(words[1]);
}
}
}
if (input_product_size > 1) {
}
}
System.out.println(finalprice);
}
}
im thinking about a 2D array or even a hashmap of lists but im sure the best way to approach this here. Any pointers would be appreciated!
Create a class to represent each product, like so:
public class Product {
private String name;
private double price;
private Product[] ingredients;
...
public Product(String name, double price, Product... ingredients) {
// populate instance variables
}
}
I can't tell what your input is supposed to be, so obviously you might have more fields in the class. It looks like it's in CSV format but it's severely malformed. You can add getters and setters as needed.
After you've created that class you can simply make a List<Product> and populate it with the values from your input.
long edit:
Using your sandwich example, we have the input sandwich,10,6,mayonnaise;sand;bread;mozzarella;bacon;salt. Splitting it on the commas gives us this array:
["sandwich","10","6","mayonnaise;sand;bread;mozzarella;bacon;salt"].
Let's just assume this array is called words like it is in your code. Product#name for a given instance would be words[0], Product#price would be words[1], and so on. You'll also have to split words[3], or your list of ingredients, on the semicolons and pass those in.
You'll also have to find a way to construct Product objects from those names, because right now, you don't know what the prices of those ingredients are. One decent way to do this would be to create a "cache" of known Products and search through it by name. The other way would be to provide the prices of the ingredients in the input.
Hopefully this clears things up some. I know it's a long read.

Java array in for loop

I'm trying to create a menu for toll data entry that runs in a loop until the user requests to exit. The menu will ask the user to enter data which is stored in an array and keeps adding to the array until the user exits from the menu.
The menu should look as follows:
Toll Data Entry Menu
My menu works fine until asking the user to enter the trip date. The menu will continue to ask for each trip date up until the end of the length of the array (30 - arbitrary length).
I however want the menu to ask for the trip date, store the value entered by the user, then move onto entering the entry point, store value, etc and then loop back to the selection for the user to enter the above details again for a separate trip until they choose to exit. (I need to print these values later on) I'm not sure how to store the values from the user separately without prompting the user to enter all (30) values at the one time.
Should I be using an array or is there another way to store multiple values for a looped menu?
Hope my explanation is clear.
To fetch the complete set of details one at a time, you just need a single for loop as:
String[] datesA = new String [30];
int[] entryP = new int [30];
int[] exitP = new int [30];
for (int i = 0; i < 30; i++) {
System.out.println("Enter trip date: ");
datesA[i] = inputA.nextLine();
// User to enter entry point
System.out.println("Enter entry point: ");
entryP[j] = inputA.nextInt();
// User to enter exit point
System.out.println("Enter exit point: ");
exitP[k] = inputA.nextInt();
}
To improve the implementation though think over the lines of creating an object that includes all the details in one as :
class TollDataEntry {
String entryDate;
int entryPoint;
int exitPoint;
.... getter, setter etc.
}
and then use an array or Collection of this object to store the details of each TollDataEntry with those three values as a single entity.

My code is not working well

import java.util.Scanner;
public class NewClass {
public static void main(String[]args){
Scanner input=new Scanner(System.in);
String productMin="";
System.out.print("How much money do you have? ");
double money=input.nextDouble();
double minPrice=0;
double total=0;
double productPrice;
System.out.print("Please, insert the items in the invoice (the
name of product and its price):\n Insert \\\"stop\\\" as the name of
product to finish your input \n");
String productName=input.next();
productPrice=input.nextDouble();
total=total+productPrice;
while(!input.next().equals("stop"))
{
if(minPrice<productPrice)
{
minPrice=productPrice;
productMin=productName;
}
productName=input.next();
total=total+productPrice;
}
if(total<=money)
{
System.out.println("You have enough money !");
System.out.printf("%s is the item with the minimum price(which is SR
%.3f)\n",productMin,minPrice);
}
else
System.out.println("You don\'t have enough money");
System.out.println(total);
}//end of main method
}//end of calss
This is my code and it is not giving me the minimum price of the product and its name I tried a lot of things but still nothing and I'm running out of time can someone tell me where is the mistake????
This how the output should be
How much money do you have? 100
Please, insert the items in the invoice (the name of product and its price): Insert \"stop\" as the name of product to finish your input
Banana 20.200
Water 15.300
Honey 37.500
stop
You have enough money
Water is the item with the minimum price (which is KD 15.300)
And this my output
How much money do you have? 100
Please, insert the items in the invoice (the name of product and its price):
Insert \"stop\" as the name of product to finish your input
ss 20.100
dd 15.200
ff 37.500
stop
You have enough money !
ss is the item with the minimum price(which is SR 20.100)
in this line
while(!input.next().equals("stop"))
what happens if the user did not enter stop? - he/she still entered something...
You simply forgot to take the product price as an input in your while loop, you are taking it as a string.

Categories