【发布时间】:2014-04-09 17:31:17
【问题描述】:
我正在使用基于控制台的 java 制作学生系统。我正在尝试将文本文件的内容加载到 ArrayList 中,然后使用学生注册号进行搜索并列出他/她的姓名和程序。 我很难将文本文件内容加载到 ArrayList 中,以便以后可以将它们作为对象检索。
我已经制作了一个在 Arraylist 上完美运行的搜索功能(因为当输入新记录时,我将它们放入 ArrayList 并且可以搜索它们直到程序没有关闭)
这是我尝试在 ArrayList 中加载文本文件的方法:
try {
ArrayList<NewStudent> student = new ArrayList<>();
BufferedReader inFile = new BufferedReader (new FileReader ("Test.txt"));
String inputLine;
while ((inputLine = inFile.readLine())!=null) {
NewStudent ns = new NewStudent();
String[] studentVars = inputLine.split(":");
ns.setName(studentVars[0]);
student.add(ns);
}
System.out.print(student);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是我的搜索方法,这就像一个魅力
public Student Search(String ID, ArrayList<Student> StudentList) {
Student myStudent = new Student();
for(int i=0 ; i<StudentList.size() ; i++) {
if(StudentList.get(i).getID().equals(ID)) {
myStudent.setID(StudentList.get(i).getID());
myStudent.setName(StudentList.get(i).getName());
myStudent.setProgram(StudentList.get(i).getProgram());
return myStudent;
}
}
return null;
}
打印时,它会打印:
[com.Student.NewStudent@615e7597, com.Student.NewStudent@7a3e72, com.Student.NewStudent@5999ae9c, >>com.Student.NewStudent@7896b1b8, com.Student.NewStudent@6d6de4e1, com.Student。 NewStudent@49cda7e7, com.Student.NewStudent@5cca548b]
如果我使用不同的方法:
BufferedReader inFile = new BufferedReader (new FileReader ("Student.txt"));
ArrayList<String> arrayList = new ArrayList<>();
String inputLine;
while ( (inputLine = inFile.readLine() ) != null) {
String[] stud = inputLine.split(":");
arrayList.add(stud[0]); \\if I add stud[1] it gives null pointer exception
}
System.out.println(arrayList);
这不会作为单独的对象返回。它显示一条直线
这就是我的文本文件的样子
1112149 亚历克斯 BSCS
1112155 塔玛拉 BSCS
1112154 凯西 工商管理硕士
1112114 约翰 BABS
每个对象都在不同的行
【问题讨论】:
-
那有什么问题?
-
你的代码应该做什么?它的实际作用是什么?
-
我忘记写问题了。现在我已经编辑了它。要是人们在投反对票之前给我们一些新人时间就好了
-
在第一种情况下,您正在创建
arraylist类型为NewStudent的对象。在第二个中,您只是在创建arraylistofString。所以显然不会有任何对象,只会打印出字符串 -
@GoldRoger 我在学生 Bean 类的 setName 设置器中使用该字符串