假设我们有一个这样的文本文件:
我要做的是使用DatePeople和DateComparator类(使用collection.sort)按降序生成列表
我真正理解的是在阅读txt文件之后如何以正确的方式将它们作为DatePeople对象放入arraylist?
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();
}
DatePeople:
public class DatePeople
{
DatePeople(){
}
private String name;
private int day;
private int month;
private int year;
}
DateComparator:
public class DateComparator implements Comparator<DatePeople> {
public DateComparator(){
}
@Override
public int compare(DatePeople o1, DatePeople o2) {
return 0;
}
}
答案 0 :(得分:0)
您需要先为每一行创建一个对象,然后才能将其添加到对象列表
while (s.hasNext()){
//create your DatePeople object here
// then add it to the list
DatePeople obj = new DatePeople(name,year,month,day);
list.add(obj);
//list.add(new DatePeople(name,year,month,day)); something like this i guess ?
}
s.close();
您还需要在DatePeople类中创建一个带有名称,年,月,日参数的构造函数。
目前,您有一个年,月,日三个变量。不确定这是否是故意的。或者你可以在你的班级中拥有名字和日期变量。