从阅读文件中分割结果的更好方法是什么?

时间:2012-10-07 01:23:16

标签: java arrays arraylist split

我有一个读取文件的函数,并将结果收集到数组列表中。 数组列表看起来像这样(数据)

  

[12,adam,1993,1234,bob,1992]

然后我需要将这些细节加载到称为患者的新对象中。这是我到目前为止将每个单独的数组列表项放入其自己的患者中的当前方法,但它一直在告诉我一个错误,说我在String String Int中传递,并且它需要是一个String。

s看起来像这样

  

12,亚当,1993年

这是代码

public void loadPatients()throws Exception
{
    ArrayList<String> data = IO_Support.readData("PatientData.txt");

    System.out.println(data);
    for(String s : data)
    {
        Sytem.out.println(s);
        patientList.add(new Patient(s));
    } 
}

有没有办法将我的数组列表结果推送到字符串中以传入患者对象,或者我应该使用不同的方法来分割字符串结果?

读取数据看起来像这样

public static ArrayList<String> readData(String fileName) throws Exception
{
    ArrayList<String> data = new ArrayList<String>();
    BufferedReader in = new BufferedReader(new FileReader(fileName));

    String temp = in.readLine(); 
    while (temp != null)
    {
        data.add(temp);
        temp = in.readLine();   
    }
    in.close();
    return data;
}

1 个答案:

答案 0 :(得分:1)

while (temp != null)
{
    temp = in.readLine();   
}

第一件事,你永远不会把你的输入添加到ArrayList ..这个while循环毫无意义..它只是读取用户输入,并在每个场合吞下它..

加号,在看到您的例外后,确定您使用的1-arg constructor Patient class不在那里..只有0-arg constructor2-arg constructor课程中的Patient ..您确实需要使用它们。

loadPatient方法中查看此代码..您需要在患者类中添加 1-arg构造函数以进行编译..

patientList.add(**new Patient(s)**); --> Will not work

因此,在您的Patient类中,添加: -

public Patient(String s) {
    this.s = s;
}

this.s是用于存储您传递的s的实例变量..

相关问题