Cannot find symbol method

1.2k Views Asked by At

Upon compiling, I get the error of cannot find symbol - method add(java.lang.String). The goal of the code so far is just to add a new flavour to the ArrayList. I am using the BlueJ IDE, monstrous I know!

import java.util.ArrayList;

public class IceCream
{
    // stores ice cream flavours.
    private ArrayList<String> flavours;

    /**
     * Constructor for objects of class IceCream
     */
    public IceCream()
    {
        // initialise instance variables
        flavours = new ArrayList<String>();
    }

    /**
     * Method to add a flavour to the list.
     */
    public void newFlavour(String flavours)
    {
        flavours.add(flavours);        
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

You named the String parameter equal to the attribute's name (flavours), so the compiler tries to lookup the add() method in the String class (which is not available). Change the code like:

public void newFlavour(String flavours)
{
    this.flavours.add(flavours);        
}

or use different names.

0
On

Look at the code:

public void newFlavour(String flavours)
{
    flavours.add(flavours);        
}

The parameter flavours is shadowing your field flavours, so the compiler is trying to find an add method in String, not ArrayList. You could just explicitly qualify it (this.flavours.add(flavours)) but it would be much better to change the parameter name. After all, you're not adding multiple flavours - just one... so your parameter name should reflect that:

public void newFlavour(String flavour)
{
    flavours.add(flavour);
}

And possibly change the method name to addFlavour, too.