不确定这在哪里抛出异常,但基本上我正在尝试隔离分数,以便我可以在可比较的函数中调用分数,并按分数的顺序打印出关联的名称和分数。
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();
}
}
最佳答案
首先,您永远不会关闭 Scanner
(并且您可以将 File
传递给 Scanner
构造函数,因此不需要 >FileReader
) - 我将使用 try-with-Resources
来确保文件句柄已关闭。其次,您需要使用(并跳过)文件中的 header 。最后,我会使用 String.lastIndexOf(String)
而不是尝试找到第二个空格(只需找到最后一个)。比如,
public void loadDataFromFile(String fileName) throws FileNotFoundException {
try (Scanner in = new Scanner(new File(fileName))) {
if (in.hasNextLine()) {
in.nextLine(); // consume header
}
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.isEmpty()) {
continue; // skip empty lines.
}
int p = line.lastIndexOf(" ");
String name = line.substring(0, p);
int studentScore = Integer.parseInt(line.substring(p + 1));
Student s = new Student(name, studentScore);
student_list.add(s);
}
}
}
关于java - 如何从文件中逐行读取,在第二个空格后拆分,以便将名称和分数分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60233424/