从 .txt 文件中的学生列表计算平均值

Calculating Average from a list of students taken from a .txt file

我有一个单独的 .txt 文件,其中有一个 "students" 的列表,边上有自己的标记,从 0 到 10,这里是 .txt 的示例:

Mark 2
Elen 3
Luke 7
Elen 9
Jhon 5
Mark 4
Elen 10
Luke 1
Jhon 1
Jhon 7
Elen 5
Mark 3
Mark 7

我想做的是计算每个学生的平均值(以 double 表示),以便输出如下所示:

Mark: 4.0
Elen: 6.75
Luke: 4.0
Jhon: 4.33

这是我想出来的,目前我只设法使用 Properties 来列出学生姓名而不重复,但每个人旁边显示的数字是显然是程序找到的最后一个。
我在实现 GUI 时将它包含在按钮 actionlistener 中,通过按下按钮,上面显示的输出是 append in a TextArea:

 b1.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent d) {

   try {
      File file = new File("RegistroVoti.txt");
      FileInputStream fileInput = new FileInputStream(file);
      Properties properties = new Properties();
      properties.load(fileInput);
      fileInput.close();

      Enumeration enuKeys = properties.keys();
      while (enuKeys.hasMoreElements()) {
        String key = (String) enuKeys.nextElement();
        String value = properties.getProperty(key);
        l1.append(key + ": " + value + "\n");
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
});

我想用Collectors来计算平均值,但实际上我不知道如何实现...

感谢任何帮助!

提前致谢!

我喜欢做这种事情的方式是使用 Maps 和 Lists。

要从文件中读取行,我喜欢 nio 的读取方式,所以我会

List<String> lines = Files.readAllLines(Paths.get("RegistroVoti.txt"));

然后,你可以制作一个HashMap<String,List<Integer>>,它将存储每个人的名字和与他们相关联的号码列表:

HashMap<String, List<Integer>> studentMarks = new HashMap<>();

然后,使用 for each 循环遍历每一行并将每个数字添加到哈希映射中:

for (String line : lines) {
    String[] parts = line.split(" ");
    if (studentMarks.get(parts[0]) == null) {
        studentMarks.put(parts[0], new ArrayList<>());
    }
    studentMarks.get(parts[0]).add(Integer.parseInt(parts[1]));
}

然后,您可以遍历映射中的每个条目并计算关联列表的平均值:

for (String name : studentMarks.keySet()) {
    System.out.println(name + " " + studentMarks.get(name).stream().mapToInt(i -> i).average().getAsDouble());
}

(请注意,这是一个 Java 8 stream 的解决方案;在早期版本中,您可以轻松地编写一个 for 循环来计算它)

有关我使用过的一些东西的更多信息,请参阅:

希望对您有所帮助!

编辑 完整的解决方案:

b1.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent d) {
        try {
            List<String> lines = Files.readAllLines(Paths.get("RegistroVoti.txt"));

            Map<String, List<Integer>> studentMarks = new HashMap<>();

            for (String line : lines) {
                String[] parts = line.split(" ");

                if (studentMarks.get(parts[0]) == null) {
                    studentMarks.put(parts[0], new ArrayList<>());
                }
                studentMarks.get(parts[0]).add(Integer.parseInt(parts[1]));
            }

            for (String name : studentMarks.keySet()) {
                System.out.println(name + " " + studentMarks.get(name).stream().mapToInt(i -> i).average().getAsDouble());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});