randompwner
randompwner

Reputation: 11

Adding to an ArrayList of objects?

Just for starters this is for school. Not looking for an answer but I'm lost when adding both the date and weight into an object and then adding that object into an arraylist.

public void addEntry(String d, int w) {
    Diet dietConstructor = new Diet();
    entries = new Entry(d, w);
    diet.add(entries);
}

This method is what is adding to an object and then into an arraylist.

I'm not sure if it is adding objects into an arraylist incorrectly or if when I am trying to print the values and it is just calling the last entered and printing that. Below is where I am trying to print the values.

public void viewList()
{
    String output = "";

    weightDiff = 0;

    for (int i = 0; i < diet.size(); i++)
    {
        weightLossOrGain = entries.getWeight();

        System.out.print("  " + diet.get(i) + "\t      ");
        System.out.print(diet.get(i) + "\t   ");

        System.out.print(weightDiff + "\n\n");

        weightLossOrGain -= entries.getWeight();
    }

    System.out.println("-------------------------------\n");
    System.out.println("Net Weight Loss/Gain = " + weightLossOrGain + "\n");
    System.out.println("-------------------------------\n\n");

}

Upvotes: 0

Views: 92

Answers (1)

Harshal Parekh
Harshal Parekh

Reputation: 6017

By what I understand from your question, you are re-using entries as an object to add the object to the ArrayList.

You are adding the object to the ArrayList correctly, there is no bug there.

You're not actually accessing the weight from the ArrayList, you're accessing the weight of the last object made which is why you are just getting the value of the last object.

I do not understand your end goal correctly here. But here is what you should modify in the viewList function:

weightLossOrGain -= diet.get(i).getWeight();

Upvotes: 1

Related Questions