I'm trying to read a text file to an arrayList but it's telling me
"no suitable method found for add(string) method Collection.add(Animal) is not applicable (argument mismatch; String cannot be converted to Animal)"
I have a class called Animal and within that this is my constructor code
//Constructor
public Animal(String aType, String aColor, boolean aVertebrate, boolean aFly, boolean aSwim) {
type = aType;
color = aColor;
vertebrate = aVertebrate;
fly = aFly;
swim = aSwim;
}
In my main class this is the code I'm using to read the text file
else if (menuSelection.equalsIgnoreCase("I")){
Animal a;
String line;
try (BufferedReader br = new BufferedReader(new FileReader("animalFile.txt"))){
if (!br.ready()){
throw new IOException();
}
while((line = br.readLine()) != null){
animalList.add(line);
}
br.close();
}catch (FileNotFoundException f){
System.out.println("Could not find file");
}catch (IOException e){
System.out.println("Could not process file");
}
int size = animalList.size();
for (int i = 0; i < animalList.size(); i++) {
System.out.println(animalList.get(i).toString());
}
I'm getting the error message on the "animalList.add(line)"
The list animaList
is a list of Animal
. BufferedReader readLine() returns String
, therefore you cannot add a String
to a list of Animal
.
In this line you should a call a method that converts the string to an animal object.
while((line = br.readLine()) != null) {
Animal animal = getAnimal(line);
animalList.add(animal);
}
The method would like:
private Animal getAnimal(String in) {
// Split string and initialize animal object correctly
}