java - 如何从文件中逐行读取,在第二个空格后拆分,以便将名称和分数分开?

标签 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();
    }
}

Text file that I'm reading from

最佳答案

首先,您永远不会关闭 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/

相关文章:

java - 如何处理 Spring data mongodb 中的 DuplicateKeyException

java - 当我启动 hazelcast/bin/run.bat 时 TestApp 出现 ClassNotFoundException

java - Android getSystemService 函数的解决方案

java - 在数据表中使用过滤器进行动态计算

java - 在 Java 中使用 XML 发出 HTTPS Post 请求

java - 从前端应用程序查询其余后端应用程序时避免基本身份验证弹出窗口

java - 为什么jdbc中数据库url必须采用特定格式?

java - 禁用字符串转义(反斜杠 hell )

java - 无法将 Java 项目性质添加到嵌套 m2Eclipse 项目

java - 当模式涉及美元符号 ($) 时的正则表达式