java如何从文件中读取行,在第二个空格后拆分,以便将名称和分数分开?
不确定这是在哪里引发异常,但基本上我正在尝试隔离分数,这样我就可以在一个可比较的函数中调用分数,并按照分数的顺序打印出相关的名称和分数
public void loadDataFromFile(String fileName) throws FileNotFoundException {
FileReader reader = new FileReader(fileName);
Scanner in = new Scanner(reader);
while(in.hasNextLine()) {
String line = in.nextLine();
String name = line.substring(0, line.indexOf(' ', line.indexOf(' ') + 1));
String score = line.substring(line.indexOf(name));
int studentScore = Integer.parseInt(score);
Student s = new Student(name, studentScore);
student_list.add(s);
}
}
public void printInOrder() {
Collections.sort(this.student_list);
for(Student s : student_list) {
s.toString();
}
}
# 1 楼答案
首先,您永远不会关闭} 而不是试图找到第二个空格(只找到最后一个)。比如
Scanner
(并且您可以将File
传递给Scanner
构造函数,因此不需要FileReader
)-我会使用try-with-Resources
来确保文件句柄已关闭。其次,您需要使用(并跳过)文件中的头。最后,我将使用^{