Having trouble adding together elements from array - java

I have to write a program that uses two classes to create a grocery list. The first class creates an array to hold the values gotten from the second class. The array holds grocery items which have a name, quantity, and price value. I have a function that is supposed to get a total cost of everything in the array, but for some reason the function is only adding the last item that is added to the array to itself. Here's my code:
public class GroceryList {
private GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
private int numofEntries;
public GroceryList()
{
this.groceryList = new GroceryItemOrder[10];
this.numofEntries = 0;
}
public void add(GroceryItemOrder item)
{
if(numofEntries == 10)
{
System.out.println("The list is full.");
}
else
{
groceryList[numofEntries] = item;
numofEntries++;
}
}
public double getTotalCost()
{
double totalCost = 0;
double newCost = 0;
for(int size = 0; size < numofEntries; size ++)
{
newCost = groceryList[size].getCost();
totalCost = newCost + totalCost;
}
return totalCost;
}
public class GroceryItemOrder {
private static double pricePerUnit;
private static int quantity;
private String name;
public GroceryItemOrder(String name, int quantity, double pricePerUnit)
{
this.name = name;
this.quantity = quantity;
this.pricePerUnit = pricePerUnit;
}
public static double getCost()
{
return (quantity * pricePerUnit);
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public static void main(String[] args)
{
GroceryList newList = new GroceryList();
newList.add(new GroceryItemOrder("cookies", 1, 1.50));
newList.add(new GroceryItemOrder("cheese", 2, 1.0));
newList.add(new GroceryItemOrder("bread", 1, 5.0));
System.out.println(newList.getTotalCost());
}
}
In the function I was trying to use a for loop that would run through the array one element at a time and take whatever values were stored into the element and store it into a new object. I feel like I'm heading in the right direction but can't figure out where the issue is with the function. Can anyone see where my issue is, or at least give me some advice on how I can begin to attempt to fix the issue?

2 of your 3 variables in GroceryItemOrder are static, which means only one variable for the entire class, not one for each instance. Each new instance overwrites the values set by the previously created instance.
Make all of those instance variables not static:
private double pricePerUnit;
private int quantity;
private String name;

The static modifier to quantity and pricePerUnit makes no sense if you want to have some variety in your grocery. What happens is that each time you call the constructor or GroceryItemOrder, you change those two static fields, so if affects the total price of all the previous orders created. The rest is fine even if it could be more concise sometimes.

Related

How do I access the itemPrice part of this array?

So I need to grab the itemPrice part of the index and add them all together, but i'm not sure how to go about accessing that. Can I somehow use my getCost method from the GroceryItemOrder class and continuously add it to the totalCost in the GroceryList class, or do I need to access the itemPrice and quantity part of each stored object.
public class GroceryList {
public GroceryItemOrder[] groceryList = new GroceryItemOrder[0];
public int manyItems;
public GroceryList() {
final int INITIAL_CAPACITY = 10;
groceryList = new GroceryItemOrder[INITIAL_CAPACITY];
manyItems = 0;
}
//Constructs a new empty grocery list array
public GroceryList(int numItem) {
if (numItem < 0)
throw new IllegalArgumentException
("The amount of items you wanted to add your grocery list is negative: " + numItem);
groceryList = new GroceryItemOrder[numItem];
manyItems = 0;
}
public void add(GroceryItemOrder item) {
if (manyItems <= 10) {
groceryList[manyItems] = item;
}
manyItems++;
}
//
// #return the total sum list of all grocery items in the list
public double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ ) {
//THIS PART
}
return totalCost;
}
}
And this is GroceryItemOrder
public class GroceryItemOrder {
public String itemName;
public int itemQuantity;
public double itemPrice;
public GroceryItemOrder(String name, int quantity, double pricePerUnit) {
itemName = name;
itemQuantity = quantity;
itemPrice = pricePerUnit;
}
public double getcost() {
return (itemPrice*itemQuantity);
}
public void setQuantity(int quantity) {
itemQuantity = quantity;
}
public String toString() {
return (itemName + " " + itemQuantity);
}
}
Thanks for all the replies! I got it working and understand what's going on here now.
You first need to access an instance of GroceryItemOrder in the array and from there then access its itemPrice field like so,
groceryList[0].itemPrice
would give you the itemPrice of the first groceryListOrder in the groceryList array. If you want to use a method to do this instead, then add a getItemPrice method in your groceryListOrder class,
public getItemPrice() {
return itemPrice;
}
Then you can access each groceryListOrder's itemPrice in the array like so,
groceryList[0].getItemPrice()
would do the same as groceryList[0].itemPrice. If you wanna get the total cost of all the objects in the groceryList array, then use a loop to add all the itemPrice fields multiplied by the itemQuantity field (since it's the totalcost of each object being summed together) by using your getcost method,
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++) {
totalCost += groceryList[i].getcost();
}
First of all you should encapsulate all fields ofGroceryItemOrder class, so all the fields should be private member of the class and then use their setter/getter methods to access them in GroceryList.
Secondly, this implementation has a bug. The second constructor gets numItem as input and initialize array size accordingly. But, add method does not look at the real size and that might cause invalid array index exception. Consider this code:
GroceryList list = new GroceryList(2);
for (int i=0; i<10; i++)
list.add(new GroceryItemOrder("grocery", 5, 10));
The exception will be occurred when i=2
This works for me, you would need to set static GroceryItemOrder[] groceryList = new GroceryItemOrder[0]; as well:
//
// #return the total sum list of all grocery items in the list
public static double getTotalCost() {
double totalCost = 0;
for (int i = 0; i < groceryList.length; i++ )
{
totalCost += groceryList[i].getcost();
}
return totalCost;
}

Using superclass method to calculate price

I am doing a problem on inheritance and hierarchy of classes.
The problem is this: I have superclass that contains quantity as the attribute.
The code for that class is here:
class Items {
private int quantity;
public Items(int quantity) {
this.quantity = quantity;
}
Then i have two subclasses that contains prices and other attributes.
Code snippet:
class Coffee extends Items {
private String size;
public Coffee (int quantity, String size) {
super(quantity);
this.size = size;
}
}
class Donuts extends Items {
private double price;
private String flavour;
public Donuts(int quantity, double price, String flavour) {
super(quantity);
this.price = price;
this.flavour = flavour;
}
}
What i want to do is calculate the total price for each object.
My program reads a text file and creates object and stores them in an arrayList. The text file i am reading is this, Please note i have commented the first two lines just to explain what each token is, They are not included in the real file.:
Coffee,3,medium // name of item then the quantity and then size
Donut,7,0.89,chocolate // name then quantity then price then flavor
Donut,3,1.19,eclair
Coffee,1,large
I want to calculate the total price without duplication of the code. What i have done so far in my superclass is this:
public double totalPrice(Items x) {
double total = 0;
if(x instanceof Coffee) {
total = getQuantity() * getSizePrice();
} else {
if (x instanceof Donuts) {
total = totalPrice();
}
}
return total;
}
public abstract String getSizePrice();
In my Coffee subclass:
public double getSizePrice() {
double priceSmall = 1.39;
double priceMed = 1.69;
double priceLar = 1.99;
if(size == "small") {
return priceSmall;
} else {
if (size == "medium" ) {
return priceMed;
}
}
return priceLar;
}
I believe i am going in circles with this one so i was wondering if the SO community could guide me in the right direction. If the question is confusing, feel free to ask and i would explain it further.
Is it possible to get a totalPrice() method in each class and then through ploymorphism the class calculates the price of those items in the main method.

How to change the position within the array

I have one class which is called people where I keep track of 50 people, their rank, name, age and order. Then I have a second class called rearrange where I have to change the position of the int order. So it will change up the order, like order 1 which is in position 0, will be moved to position 48th. I need to do the whole thing without using any loop.
class people {
int order[] = new int[50];
for(int j=0; j<order.length; j++) {
order[j] = "order" + j;
System.out.print(order);
}
}
class rearrange {
// In here i need to change the position of the int order, and need to do this without using any loop.
}
Shouldn't rearrange be a method of the people class? Classes are usually created for Nouns, Verbs are usually functions or methods of a class. And wouldn't it be better to have a class "Person" and make an array of 50 of them, and simply change their index to change their order?
Consider something like this:
public class Person //create Person class with the attributes you listed
{
private int rank;
private int age;
private String name;
public Person(int rank, int age, String name) //constructor
{
this.rank = rank;
this.age = age;
this.name = name;
}
}
public class MainClass
{
Person[] people = new Person[50]; //array of Persons, containing 50 elements
public static void main(String[] args)
{
for(int i = 0; i < people.length(); i++)
{
people[i] = new Person(something, something, something); //give all the people some values, you'll have to decide what values you are giving them
}
//do something with the rearrange function here
}
public static void rearrange(int target, int destination) //this is just a "swap" function
{
Person temp = people[destination];
people[destination] = people[target];
people[target] = temp;
}
}

What am I doing wrong - trying to multiply an int and a double

I am trying to multiply the units by the price, but I cannot seem to do it. Here is the code:
import java.math.*;
public class FrameArray
{
private String frameInventory;
private int[] units;
private double[] price;
public FrameArray( String frame, int[] unitsArray, double[] priceArray, double value )
{
frameInventory = frame;
units = unitsArray;
price = priceArray;
}
public void setFrameInventory( String frame )
{
frameInventory = frame;
}
public String getFrameInventory()
{
return frameInventory;
}
public double totalValue(double value)
{
value = totalValue(value);
value = units * price;
}
public void displayMessage()
{
System.out.printf( "Current frame inventory\n\n");
}
public void processInventory()
{
outputInventory();
}
public void outputInventory()
{
System.out.println( "Inventory levels:\n");
System.out.printf( "Style Qty Price\n\n");
for (int frame = 0; frame < price.length; frame++)
System.out.printf( "Frame %2d: %3d %5.2f\n", frame + 1, units[ frame ], price[ frame], totalValue(frame) );
}
}
I am having the problem with the units * price portion. What am I doing incorrect?
Your function is stuck in an endless loop!
public double totalValue(double value)
{
value = totalValue(value); // Calls your function again and again
value = units * price;
}
You would likely want to do something like this :
public double totalValue()
{
return units * price;
}
However units and price need to be of type double or any other suitable type. In your code it are arrays. Also your argument value seems a bit weird to me in a totalValue function. Isn't that what it has to return (the total price) ?
EDIT : units and price are arrays of double, which means these arrays contain elements of type double. Hence I presume that what you want to do is something like, return units[correspondingIndex] * price[correspondingIndex];, hence multiplying double's.

Iterating through an arraylist of objects

I am working on a project that has a class called Items and a method called totals that calculates a grand total for an array of Items objects.
for some reason it cant see Items, I know that I am missing something simple or obvious but I just cant figure it out. Ant help would be appreciated.
public void totals(){
int index=0;
for (Iterator it = items.iterator(); it.hasNext();) {
Items i = it.next();
double itotal;
itotal = items.get(index).Items.getTotal();
}
}
and here is the Items class
public class Items {
public String name;//instance variable for item name
public int number;//instance variable for number of item
public double price;//instance variable for unit price
public double total;//instance variable for total
Items(String name,int number,double price){
this.name=name;
this.number=number;
this.price=price;
total=number*price;
}
public void setName(String name){
this.name=name;
}
public void setNumber(int number){
this.number=number;
}
public void setPrice(double price){
this.price=price;
}
public void setTotal(){
total=number*price;
}
public String getName(){
return name;
}
public int getNumber(){
return number;
}
public double getTotal(){
return total;
}
public double getPrice(){
return price;
}
Thanks in advance for the help.
Basically, there are two flaws:
you never increment the itotal variable and it's declared inside the loop
you never access the variable i in the current iteration
And also, shouldn't your totals method return something (like itotal)?
The way I see it, the proper way of iterating over that items array is
public double totals(){
double itotal = 0.0; //#A
for (Iterator<Items> it = items.iterator(); it.hasNext();) { //#B
Items i = it.next(); //#C
itotal += i.getTotal(); //#D
}
return itotal; //#E
}
Basically:
#A Here you initialize the itotal variable (outside of the loop) that will contain the grand total for all items
#B You start iterating over all items
#C You get the next item in the array
#D You increment the grand total with the current item's total
#E You return the grand total
There are a number of potential issues here.
In your for loop, you declare Items i, but never use it. Maybe it = it.next() should be a part of the for loop instead?
You call items.get(index), but index is always 0. You might want to use it here instead.
You declare double itotal and assign it within the for loop, so it's overwritten on each iteration. Maybe you want to declare it with an initial value outside the loop, and then increment it inside the loop.

Categories

Resources