create a class called Student. Every Student will contain a name (String) and an ArrayList<String> storing hobbies. Then, you will add all those students from the file into an ArrayList<Student>, with each Student having a separate name and ArrayList of hobbies. Here is an example file containing students (the first line will always represent yourself). NOTE: eventually, we will have a different file containing all our real names and hobbies so that we could find out with how many people each of us share the same hobby. Vitaly,table tennis,chess,hacking Sean,cooking,guitar,rainbow six Nolan,gym,piano,reading,video games Jack,cooking,swimming,music Ray,piano,video games,volleyball Emily,crochet,drawing,gardening,tuba,violin Hudson,anime,video games,trumpet Matt,piano,Reading,video games,traveling Alex,swimming,video games,saxophone Roman,piano,dancing,art Teddy,chess,lifting,swimming Sarah,baking,reading,singing,theatre Maya,violin,knitting,reading,billiards Amy,art,gaming,guitar,table tennis Daniel,video games,tennis,soccer,biking,trumpet Derek,cooking,flute,gaming,swimming,table tennis Daisey,video games,guitar,cleaning,drawing,animated shows,reading,shopping Lily,flute,ocarina,video games,baking Stella,roller skating,sudoku,watching baseball,harp Sophie,viola,ukulele,piano,video games Step 2. Sort the student list in the ascending order of student names and print them all on the screen
时间: 2024-03-05 21:06:47 浏览: 85
LCD.rar_stm32 .s contain
Sure, here is an example implementation in Java:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
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 static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("students.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split(",");
String name = parts[0];
ArrayList<String> hobbies = new ArrayList<>();
for (int i = 1; i < parts.length; i++) {
hobbies.add(parts[i]);
}
students.add(new Student(name, hobbies));
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
Collections.sort(students, (s1, s2) -> s1.getName().compareTo(s2.getName()));
for (Student student : students) {
System.out.println(student.getName() + ": " + student.getHobbies());
}
}
}
```
This code reads the student data from a file called "students.txt" (in the same directory as the Java file), creates a `Student` object for each line, and stores them in an `ArrayList`. It then sorts the list by student name using a lambda expression, and finally prints out each student's name and hobbies using a `for` loop.
阅读全文