I am writing a toString method for my Nursery class but am having trouble getting everything working properly. I have to go through the ArrayList and call the toString method for each individual tree and then the sum for all of the trees prices. Here is what I got so far.

public String toString() {
        int sum = 0;
        Iterator i = treeList.iterator();
        while(i.hasNext()) {
            Tree iTree = (Tree) i.next();
            sum += iTree.getTreePrice();
        }
        return iTree.toString() + "The sum of the whole collection is $" + sum + ".";
    }

This doesn't work, but its just what I could bang out so far. Thanx in advance.

This doesn't work

Please explain.
Show what the code outputs now and explain what is wrong with it and show what you want it to be.

Right now I get an error saying cannot find variable iTree. It should return each tree's to method.

public String toString() {
        return "This " + treeSpecies + "'s current color is " + getCurrentColorAsString() + " and it costs $" + treePrice;
    }

and the sum of all of the trees prices.

error saying cannot find variable iTree.

What does the posted code have to do with the error message?

Please copy the full text of the error message and paste it here.

java:61: cannot find symbol
symbol : variable iTree
location: class Nursery
return iTree.toString() + "The sum of the whole collection is $" + sum + ".";
^
1 error

Is the variable: iTree in scope where you are trying to use it?
It needs to be defined outside of the {}s so its definition is at the same level of {}s where you are trying to use it.

If iTree has the value of the LAST item in treeList, why do you want to use it with the sum for the whole list?

That is where I am having the problem. I want to return the toString for the entire list, not just the last item. If I just had to print it out to the console I wouldn't have any problems, but I need to return the list.

I need to return the list.

What format for the list?
Do you want to concatenate the values returned by all the nodes's toString methods?
Define an empty String and concatenate all the values to it:
String allNodes = "";
then in the loop
allNodes += iTree.toString(); // Concatenate this tree's data to the allNodes String

then return allNodes + the rest of the stuff;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.