gpt4 book ai didi

java - 读取txt文件并将行作为对象放入List中

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:43 25 4
gpt4 key购买 nike

假设我们有一个像这样的文本文件:

我想做的是使用 DatePeople 和 DateComparator 类(使用 collection.sort)按降序生成一个列表

我真正无法理解的是,在阅读txt文件后,我如何将它们作为DatePeople对象以正确的方式放入数组列表中?

List<DatePeople> list = new ArrayList();
Scanner filenamereader = new Scanner(System.in);
System.out.println("Enter file name(input.txt): ");
String fileName = filenamereader.next();
System.out.println(fileName);
filenamereader.close();
try{
Scanner s = new Scanner(new File(fileName));

while (s.hasNext()){
list.add()); ??
//list.add(new DatePeople(name,year,month,day)); something like this i guess ?
}
s.close();

}catch(IOException io){

io.printStackTrace();
}

约会对象:

public class DatePeople
{

DatePeople(){

}
private String name;
private int day;
private int month;
private int year;


}

日期比较器:

public class DateComparator implements Comparator<DatePeople> {
public DateComparator(){

}

@Override
public int compare(DatePeople o1, DatePeople o2) {




return 0;
}
}

最佳答案

如果你知道数据是标准化的,那么你就可以根据已知的规则来解析它。

String line = s.nextLine();
String[] bits = line.split(" ", 2);
String name = bits[0];
String[] dateBits = bits[1].split("-", 3);
int year = Integer.parseInt(dateBits[0]);
int month = Integer.parseInt(dateBits[1]);
int day = Integer.parseInt(dateBits[2]);

list.add(new DatePeople(name, year, month, day));

然后您需要一个构造函数,用于在 DatePeople 中传递值,即:

DatePeople(String n, int y, int m, int d) {
this.name = n;
this.year = y;
this.month = m;
this.day = d;
}

或者,您可以在 DatePeople 中有一个 parseDatePerson(String line) {} 方法,其中包含我的第一个代码段,然后您只需输入

list.add(new DatePeople(s.nextLine()));

这将调用 DatePeople 中的构造函数,如下所示:

DatePeople(String line) {
parseDatePerson(line);
}

关于java - 读取txt文件并将行作为对象放入List中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49004545/

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