Java: 将文本文件读取到数组时出错

Java: Error reading text file to array

我正在尝试将文本文件读取到 arrayList,但它告诉我

"no suitable method found for add(string) method Collection.add(Animal) is not applicable (argument mismatch; String cannot be converted to Animal)"

我有一个名为 Animal 的 class,这是我的构造函数代码

    //Constructor
public Animal(String aType, String aColor, boolean aVertebrate, boolean aFly, boolean aSwim) {
    type = aType;
    color = aColor;
    vertebrate = aVertebrate;
    fly = aFly;
    swim = aSwim;

}

在我的主 class 中,这是我用来读取文本文件的代码

    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());
             }

我在 "animalList.add(line)"

上收到错误消息

列表 animaListAnimal 的列表。 BufferedReader readLine() returns String,因此您不能将 String 添加到 Animal.

的列表中

在这一行中,您应该调用一个将字符串转换为动物对象的方法。

 while((line = br.readLine()) != null) {
     Animal animal = getAnimal(line);
     animalList.add(animal);
 }

想要的方法:

private Animal getAnimal(String in) {

// Split string and initialize animal object correctly

}

您没有显示 animalList 是什么,但从代码中,我推断它是 AnimalListbr.readLine() returns String ,但您将其添加到 animalList 中,它需要 Animal。因此,错误。

我相信 "animalList" 旨在成为 Animal 类型对象的列表。因此,当您调用 animalList.add(line) 时,它会尝试添加一个 String 对象(因为 line = br.readLine() 从文件中读取一个字符串),而 Animal 对象应该被添加。

你特别需要做的是

  1. 将字符串解析为接受 Animal 构造器(aType、aColor 等)的数据片段
  2. animalList.add(line)修改为animalList.add(new Animal(/*Put parsed parameters here*/))..