user13476915
user13476915

Reputation:

Why will java not let me use the method add() when creating a method?

The error "The method add(Shape) in the type ArrayList<Shape> is not applicable for the arguments" shows up.

I want to add data from a file to an ArrayList. Shape is the name of the abstract class and the class I'm working in is the Helper class.

I apologize, I don't know much about coding.

public static ArrayList<Shape> create(String fileName) throws FileNotFoundException, IOException{
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    ArrayList<Shape> shapes = new ArrayList<>();

    String line = br.readLine();
    while(line != null){
        shapes.add();
        line = br.readLine();
    }

    br.close();
    return shapes;
}

Upvotes: 0

Views: 72

Answers (1)

drewbie18
drewbie18

Reputation: 331

shapes is an ArrayList that takes Shape objects. When you call shapes.add() you need to supply the method with the object of type Shape to add to this list.

So I'm not sure how to construct a new Shape object I'm guessing it has something to do with what you are reading from this file. If Shape takes a String arg in the constructor...this is conjecture but...

public static ArrayList<Shape> create(String fileName) throws FileNotFoundException, IOException{
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    ArrayList<Shape> shapes = new ArrayList<>();

    String line = br.readLine();
    while(line != null){
        shapes.add(new Shape(line)); // create a new shape to add. 
        line = br.readLine();
    }

    br.close();
    return shapes;
}

Hope this helps.

Update based on your comment:

public static ArrayList<String> create(String fileName) throws FileNotFoundException, IOException{
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    ArrayList<String> shapes = new ArrayList<>();

    String line = br.readLine();
    while(line != null){
        shapes.add(line); // add String
        line = br.readLine();
    }

    br.close();
    return shapes;
}

Upvotes: 3

Related Questions