Task 2. Create a list of students by reading from student_hobbies.txt and display the list. // - You will also need to create a Student class, which has at least // two data fields: student name and an ArrayList of hobbies (String-type).优化以下代码private static ArrayList<Student> readFile(String string) throws IOException{ ArrayList<Student> studentlist=new ArrayList<Student>(); File file = new File("student_hobbies_JU.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] data = line.split(", "); System.out.println(data); String name = data[0]; ArrayList<String> hobbies = new ArrayList<String>(); for(int i=0;i<data.length;i++){ hobbies.add(data[i]); } Student student = new Student(name, hobbies); studentlist.add(student); System.out.println(student); } scanner.close(); return studentlist; }//end readFile
时间: 2024-02-14 08:08:00 浏览: 89
Studentlist.rar_studentlist
下面是优化后的代码,其中将文件名作为参数传入函数中,使函数更加通用:
```
private static ArrayList<Student> readFile(String fileName) throws IOException {
ArrayList<Student> studentList = new ArrayList<Student>();
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] data = line.split(", ");
String name = data[0];
ArrayList<String> hobbies = new ArrayList<String>();
for (int i = 1; i < data.length; i++) { // 从第二个元素开始,将所有的兴趣爱好添加到hobbies列表中
hobbies.add(data[i]);
}
Student student = new Student(name, hobbies);
studentList.add(student);
}
scanner.close();
return studentList;
}
```
该函数将指定文件中的内容读取到一个ArrayList<Student>中,并返回该列表。下面是Student类的代码:
```
public class Student {
private String name;
private ArrayList<String> hobbies;
public Student(String name, ArrayList<String> hobbies) {
this.name = name;
this.hobbies = hobbies;
}
public String getName() {
return name;
}
public ArrayList<String> getHobbies() {
return hobbies;
}
public void setName(String name) {
this.name = name;
}
public void setHobbies(ArrayList<String> hobbies) {
this.hobbies = hobbies;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", hobbies=" + hobbies +
'}';
}
}
```
该类包含两个数据字段:name和hobbies,分别表示学生的姓名和兴趣爱好列表。该类还包含构造函数、getter和setter方法以及toString方法,用于打印学生对象的信息。可以使用以下代码调用readFile函数并打印学生列表:
```
try {
ArrayList<Student> studentList = readFile("student_hobbies.txt");
for (Student student : studentList) {
System.out.println(student);
}
} catch (IOException e) {
e.printStackTrace();
}
```
阅读全文