gpt4 book ai didi

java - 从读取文件中分离结果的更好方法?

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:45 24 4
gpt4 key购买 nike

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

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

然后我需要将这些详细信息加载到称为患者的新对象中。这是我迄今为止将每个单独的数组列表项放入其自己的患者中的当前方法,但它一直用一个错误来困扰我,说我正在传入 String String Int,并且它需要是一个 String。

看起来像这样

12, adam, 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;
}

最佳答案

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

首先,你永远不会将输入添加到 ArrayList 中。这个 while 循环没有任何意义。它只是读取用户输入,并在每次情况下吞掉它。

另外,在看到您的异常后,可以确定您使用的是 Patient 类1-arg 构造函数,而该构造函数不存在。Patient 类中只有 0-arg 构造函数2-arg 构造函数。您确实需要使用它们。

请在 loadPatient 方法中查看此代码。您需要在 Patient 类中添加一个 1-arg 构造函数才能对其进行编译。

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

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

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

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

关于java - 从读取文件中分离结果的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12765353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com