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 leasttwo data fields: student name and an ArrayList of hobbies (String-type).and create readFile()
时间: 2024-02-28 09:57:07 浏览: 72
Sure, I can help you with that. Here's the code to create the Student class:
```java
import java.util.ArrayList;
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;
}
}
```
And here's the code for the `readFile()` method, which reads from the `student_hobbies.txt` file and returns a list of `Student` objects:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = readFile("student_hobbies.txt");
// Display the list of students
for (Student s : students) {
System.out.println(s.getName() + ": " + s.getHobbies());
}
}
public static ArrayList<Student> readFile(String filename) {
ArrayList<Student> students = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(":");
String name = parts[0];
String[] hobbies = parts[1].split(",");
ArrayList<String> hobbyList = new ArrayList<>();
for (String h : hobbies) {
hobbyList.add(h.trim());
}
Student s = new Student(name, hobbyList);
students.add(s);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
return students;
}
}
```
This code assumes that the `student_hobbies.txt` file has lines in the format `name:hobby1, hobby2, ...`. It reads each line, splits it into the name and list of hobbies, creates a new `Student` object with those values, and adds it to the list of students. Finally, it displays the list of students and their hobbies.
阅读全文