Keep track of price and total cost [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to keep track of each items cost, and add that to the total cost of all the items. When I run the program the last item cost and total cost is applied to each item. I feel like I should have another loop more dynamically placing the cost of each item and total cost.
Driver Class:
public class GroceryListTester
{
public static void main(String[] args)
{
GroceryList get = new GroceryList();
get.start();
}
}
CheckMail Class:
import chn.util.*;
import java.util.*;
public class GroceryList
{
//Instance variables
private int myNumItems;
private double myItemCost;
private double myTotalCost;
Scanner keyboard = new Scanner(System.in);
//Constructor
public GroceryList()
{
myNumItems = 0;
myTotalCost = 0;
}
//Methods
public void start()
{
System.out.print('\u000C');
getMyNumItems();
getMyItemPrices();
output();
}
public int getMyNumItems()
{
System.out.print("How many items would you like to purchase? => ");
myNumItems = keyboard.nextInt();
return myNumItems;
}
public double getMyItemPrices()
{
int n = 0; //Disp item number
while(n < myNumItems)
{
System.out.print("Please enter price of item #" +(n+1) +": ");
myItemCost = keyboard.nextDouble();
myTotalCost = myTotalCost + myItemCost;
++n;
}
return myTotalCost;
}
public void output()
{
for(int n = 0; n < myNumItems; ++n)
{
System.out.println();
System.out.printf("%8s %8s %8s", "Item #" +(n + 1) , "Cost: $" +myItemCost, "Total: $" +myTotalCost);
}
}
}
Output:
How many items would you like to purchase? => 3
Please enter price of item #1: 1.25
Please enter price of item #2: 1.75
Please enter price of item #3: 1.50
Item #1 Cost: $1.5 Total: $4.5
Item #2 Cost: $1.5 Total: $4.5
Item #3 Cost: $1.5 Total: $4.5

The problem is that you're not storing any reference to the price of any item but the last. This calls for a ArrayList keeping track of each item that has already been ordered.
If instead of using your int myItemCost, you used ArrayList< int> myItemCosts, and each time you added a new item you added the stated price to that List, you could print each of those items at the end.
Here's an example:
ArrayList<int> myItemCosts = new ArrayList<int>();
public double getMyItemPrices()
{
int n = 0;
while (n < myNumItems)
{
System.out.print("Please enter price of item #" + (n+1) + ": ");
myItemCosts.add(keyboard.nextDouble());
myTotalCost += myItemCost;
}
}
And then output() could be structured like so:
public void output()
{
for(int n = 0; n < myNumItems; ++n)
{
System.out.println();
System.out.printf("%8s %8s %8s", "Item #" + (n + 1) , "Cost: $" + myItemCosts[n], "Total: $" + myTotalCost);
}
}
If you decided you needed to add more function to any given grocery item, like a SKU, quantity, discount, etc., you should create your own object to encapsulate these properties:
class SampleGroceryItem
{
public SampleGroceryItem(double price, int quantity, string sku, double discount)
{
this.Price = price;
this.Quantity = quantity;
this.Sku = sku;
this.Discount = discount;
}
public double Price;
public int Quantity;
public string Sku;
public double Discount;
}
and then instantiate a new SampleGroceryItem each time the user inputs all the necessary information, and add that object to a List.

Related

Main class java does not return the value i passed in using scanner [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this main class
public class Hotel
{
Scanner scan = new Scanner(System.in);
Register[] items = new Register[15];
int count = 0;
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register deluxe = new Deluxe();
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
run.enterItems();
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
}
public double calcTotal()
{
double total = 0;
for(int i = 0;i<count;i++)
{
total += items[i].total();
}
return total;
}
that is supposed to return the value i put in in the scanner here in the enterItems() that is in the class as the main class
public void enterItems()
{
int type, quantity, sale,night;
double price;
............................
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
}
So this will pass to the class called Deluxe where i have this method called displayInfo()
public class Deluxe implements Register
{
int quantity,night;
double sale;
public Deluxe(){}
....................................
public double total()
{
double total, price = 200.0;
price = price*quantity*night;
total = price - (price * (sale/100));
total += total *.06;
return total;
}
public void displayInfo(){
if (quantity > 0){
System.out.println("Room Type : Deluxe Room");
System.out.println("Quantity: " +quantity);
System.out.println("Discount: " +sale);
}
}
}
the problem is, in checking for quantity > 0, it actually does not get any value that i put in in the scanner. It will always return 0 for quantity regardless what amount i put in.
But the calculation works fine. Calculation is to calculate how many (quantity) rooms book x night stay x the room's price.
The calculation is also in the same class as the displayInfo() which is in class Deluxe.
So i was wondering what did i do wrong here.
The quantity which you input here:
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
Goes into main(String[] args).quantity that's defined here:
public class Hotel
{
....
public static void main(String[] args)
{
...
int quantity, sale,night;
...
}
The quantity that you check here:
if (quantity > 0){...}
Is a different parameter - it's Deluxe.quantity and is defined here:
public class Deluxe implements Register
{
int quantity,night;
...
}
Those two parameters have no relation. If you want them both to be the same, you need to pass to class Deluxe the main(String[] args).quantity parameter. You can do this via your own constructor under Hotel.main(String[] args), like so:
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
quantity = run.enterItems();
Register deluxe = new Deluxe(quantity,0,0); // entering the default value for the other two parameters like the empty constructor would leave them.
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
if you change your enterItems() function to return the quantity parameter you need, like so:
public int enterItems()
{
int type, quantity, sale,night;
double price;
.........
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
return quantity;
}
Notice, this solves this only for the quantity parameter. if you need more, you might need to return the Deluxe structure from enterItems(). Good luck!

How would i program this correctly?

what the program wants me to code:
Code an executable program that will produce
an invoice for a customer ordering a number
of products at a store. A sample run of the
program is shown to the right.
Your program
must ask for the number of products (up to a
maximum of 12 products may be ordered) and
then successively ask for the product name and
its cost. The invoice produced includes:
 the title of the store (as shown),
 product names and their cost,
 calculated cost of all products,
 calculated 5% sales tax,
 overall total cost
 a thank you.
The products and their cost must be kept in
parallel arrays. Two methods must be coded.
One method will display the title. The second
method will accept the calculated cost of all
products and return the calculated sales tax.
The method that computes the sales tax must
use a named constant for the 5% tax rate.
picture of example run of what it should look like: http://imgur.com/F3XDjau
Currently my program is this so far, but im not sure if it is correct or if i need to make the variables into an array.
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int product;
String products;
double cost;
System.out.println("How many products? ");
product=input.nextInt();
for(int i = 0; i < product; i++){
System.out.println("Product Name: ");
products=input.next();
System.out.println("Cost: ");
cost=input.nextDouble();
}
}
}
this is how you can fill your array:
double[] costArray = new double[product];
for(int i = 0; i < product; i++){
costArray[i] = input.nextDouble();
}
You need to use an array for variables products and cost like this:
static final float TAXES = 0.05f;
public static void main(String[] args) {
double sum = 0.0;
double tax;
Scanner input = new Scanner(System.in);
int product;
String products[];
double cost[];
System.out.println("How many products? ");
product = input.nextInt();
products = new String[product];
cost = new double[product];
for (int i = 0; i < product; i++) {
System.out.println("Product Name: ");
products[i] = input.next();
System.out.println("Cost: ");
cost[i] = Double.parseDouble(input.next().trim().replace(',', '.'));
}
indentedText();
for (int i = 0; i < product; i++) {
System.out.printf(products[i] + '\t' + "%.2f %n", cost[i]);
sum = sum + cost[i];
}
tax = calculateTaxes(sum);
System.out.printf("Sub total:" + '\t' + "%.2f %n", sum);
System.out.printf("Sales tax:" + '\t' + "%.2f %n", tax);
System.out.printf("Total to be paid:" + '\t' + "%.2f %n %n", (sum + tax));
System.out.print('\t' + "Thank you!");
}
private static void indentedText() {
System.out.print('\t' + "The Company Store" + '\n' + '\n');
}
private static double calculateTaxes(double sum) {
return sum * TAXES;
}

How to add two values in an array?

We are just starting to learn about arrays in my Java course, so I'm having problems. I want to multiply "quantity" by "cost" so it will print out the total cost, but right now it prints out 0 for the totalCost. Here is the driver:
import java.util.Scanner;
public class Problem2 {
public static void main(String[] args){
String purchase, date;
double quantity, cost;
Scanner myScanner = new Scanner (System.in);
System.out.println("How many different types of items are you purchasing?");
int answer = myScanner.nextInt();
myScanner.nextLine(); // pick up the enter key
Basket[] myBasket = new Basket[answer];
for(int j = 0; j < answer; j++) {
System.out.println("Please enter the item you purchased.");
purchase = myScanner.nextLine();
System.out.println("Please enter the date.");
date = myScanner.nextLine();
System.out.println("Please enter the quantity.");
quantity = myScanner.nextFloat();
System.out.println("Please enter the cost.");
cost = myScanner.nextFloat();
myScanner.nextLine(); // pick up the enter key
myBasket[j] = new Basket(purchase, date, quantity, cost);
}
for (int i = 0; i< answer; i++)
{
System.out.println(myBasket[i]);
}
}
}
Here is the Basket class:
import java.text.NumberFormat;
public class Basket {
private String purchase, date;
private double quantity, cost, totalCost;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
public Basket(String purchase, String date, double quantity, double cost)
{
this.purchase = purchase;
this.date = date;
this.quantity = quantity;
this.cost = cost;
}
public void Calculations()
{
totalCost = cost * quantity;
}
public String toString()
{
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
}
Add Calculations(); to toString()
public String toString()
{
Calculations();
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
OR since the calculations method is public you can call it from the main method with myBasket[j].Calculations();
after
myBasket[j] = new Basket(purchase, date, quantity, cost);
If you want totalCost to be populated, you could call Calculations method when you are creating the instance of Baskets like:
myBasket[j] = new Basket(purchase, date, quantity, cost);
myBasket[j].Calculations();
This will now calculate the total cost and save it in in stance variable which you can print later on.
After last line in main(), add the below code,
float total=0.0;
for (int i = 0; i< answer; i++)
{
//System.out.println(myBasket[i]);
total+=myBasket[2]*myBasket[3];
}
System.out.println("total cost:"+total);
Your ”Calculations” method is not being invoked.
I thing you wanted to invoke it in the last line of the constructor.
By the way - java convention is lower case at the beginning of a method name, and it's better to name it by what it does - ”calculateTotalCost” for example

How to use arrays in this java code so I can output values in order they are assigned to positions ?

I am a java beginner and I am coding a program that gets the name of the item, units of that item, price/unit and the total price. I am trying to put those values in different arrays
so I can access them later when I create a sort of a receipt but I don't know how to assign those values in array positions and then access those same positions without having to hard-code. A loop is the best option but I dont know how to set this thing up. Help and suggestions would really be appreciated. Keep in mind that I cant do advanced stuff like matrices and 3D arrays. If you can keep it simple it would be awesome.
This is the main class, I have a tester class with main() that runs userInput() and menu() but theres no point in putting that in because its only 2 lines of code.
import java.util.Scanner;
public class GroceryList {
// instance variables
Scanner Price, Items, NumItems, Units;
private double myGross, myNet;
private final double STATETAX;
private double totalPrice, unitPrice;
private String itemName;
private int totalUnits;
///////////////////////////////////////////// arrays I will use
private double[] totalPrice1;
private double[] unitPrice1;
private String[] itemName1;
private int[] totalUnits1;
public GroceryList()
{
STATETAX = 0.06;
double[] totalPrice = new double[50];
double[] unitPrice = new double[50];
String[] itemName = new String[50];
int[] totalUnits = new int[50];
}
public void userInput()
{
Scanner Price = new Scanner(System.in);
Scanner Items = new Scanner(System.in);
Scanner Units = new Scanner(System.in);
Scanner NumItems = new Scanner(System.in);
int u, c, totalItems;// c is the number of items that has to equal totalItems in order for the loop to break
double price;
String item;//gets the name of the item
c=0;
System.out.println("Welcome to Grocery List ! \n");
System.out.print("Enter the total number of items you want to buy (not total units !) : ");
totalItems = NumItems.nextInt();
System.out.println();
do
{
c++ ;
System.out.print("Enter the item name : ");
item = Items.nextLine();
System.out.print("Enter the units of " + item + " you want to buy : ");
u = Units.nextInt();
System.out.print("Enter the price of a/n " + item + " : $");
price = Price. nextDouble();
/*this would make only one value appear at the receipt, which would be only one item name, one unit price, one price/unit, one total price and the other values calculated
would not appear on the receipt because you cant assign more than 1 value to a variable so thats why I need arrays.
*/
itemName = item;
totalUnits = u;
unitPrice = price;
calc(u,price,item);
}
while (c < totalItems);
}
public void calc(int u, double p, String i)
{
double total;//total amount of $ for 1 item
total = u*p;
System.out.println("Total price of " + i + " : $" + total + "\n");
grossPay(total);
totalPrice = total;
}
public void grossPay(double total)
{
double gross;
myGross += total;
}
public double tax()
{
double temp;
temp = myGross*STATETAX;
myNet = myGross - temp;
return myNet;
}
public void menu()
{
System.out.printf("%-10s %6s %11s %11s" , "ITEM :" , "UNITS :" , "PRICE :" , "TOTAL :");
System.out.println();
System.out.printf("%-11s %2d %7s $%4.2f %5s $%2.2f", itemName, totalUnits,"", unitPrice,"", totalPrice);
System.out.println();
}
public void payment()
{
System.out.println("Amount before tax : $" + myGross);
System.out.println("Amount after tax : $" + tax());
}
}//end GroceryList
Let's start with a little restructure ;)
First of all, you really don't need the array totalPrice1, the total price is the total price, there's only one...(IMHO)
Instead of initialising the arrays in the constructor, you should initialise them in the userInput method, this is when you know how many items the user will want to enter. Otherwise you will run into problems if I want to enter 51 items ;)
System.out.println("Welcome to Grocery List ! \n");
System.out.print("Enter the total number of items you want to buy (not total units !) : ");
totalItems = NumItems.nextInt();
System.out.println();
unitPrice1 = new double[totalItems];
itemName1 = new String[totalItems];
totalUnits1 = new int[totalItems];
(nb- You have bug in your original code, in the constructor, you had declared the arrays as local variables, but used the wrong names any way, this would leave the instance fields uninitialised, raising a NullPointerException)
While it's certainly not an error, it would simpler to increment c at the end of the loop...
do {
//...
calc(u, price, item);
c++;
} while (c < totalItems);
This will mean you don't need to constantly keep adjusting the position for the arrays.
In you "collection" loop, you need to assign the values the user has entered to each array...
do {
//...
itemName1[c] = item;
totalUnits1[c] = u;
unitPrice1[c] = price;
//...
} while (c < totalItems);
Having said all that, it would actually be easier to use something like a for-next loop...
for (int c = 0; c < totalItems; c++) {
//...
}
IMHO...
Finally, when you're ready, you can print the receipt by simply looping through the arrays...
for (int index = 0; index < totalItems; index++) {
double itemCost = unitPrice1[index] * totalUnits1[index];
System.out.println(itemName1[index] + " # " + unitPrice1[index] + " x " + totalUnits1[index] + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);
Some feedback ;)
Having said all that, I would, personally, create yourself a simple Object which contained all the required information, for example;
public class ShoppingItem {
public String name;
public double unitPrice;
public double quantity;
}
Then, all you would need is a single array, for example...
//private double[] unitPrice1;
//private String[] itemName1;
//private int[] totalUnits1;
private ShopingItem[] items;
Then, as required, you would simply create a new instance of this item and fill it out, for example...
items[c] = new ShoppingItem();
items[c] = item;
items[c] = u;
items[c] = price;
//itemName1[c] = item;
//totalUnits1[c] = u;
//unitPrice1[c] = price;
And printing the receipt would look for like...
for (ShoppingItem item : items) {
double itemCost = item.unitPrice * item.quantity;
System.out.println(item.name + " # " + item.unitPrice + " x " + item.quantity + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);
For a more "advanced" output, I would encourage you to take a look a something like String#format and/or System.out.printf
Take a look at this example for some ideas ;)
Ideally you would (wrote this as I misread your meaning of sort):
Create an Object Item which has the fields name, totalPrice, unitPrice, totalUnits. Then in your grocery list you don't need to have 4 arrays, just one array of Items. Saves the dubious task of having to keep track of indices.
If you also create an ItemComparator class that implements Comparator you can define how they should be sorted and you can then sort your array using
Collections.sort(Arrays.asList(itemsList), new ItemComparator());
You also don't need four Scanners, you can use the same scanner since they are all on System.in

How do I write a method to calculate total cost for all items in an array?

I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}

Categories