java-从.txt文件中获取的学生列表中的计算平均值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-从.txt文件中获取的学生列表中的计算平均值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2834字,纯文字阅读大概需要5分钟。
内容图文
我有一个单独的.txt文件,其中有一个“学生”列表,其侧面带有从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
我想做的是计算每个学生的平均值(用双精度表示),以便输出看起来像这样:
Mark: 4.0
Elen: 6.75
Luke: 4.0
Jhon: 4.33
这是我想出的,到目前为止,我仅设法使用Properties来列出学生姓名,而无需重复,但是显然每个人的侧面显示的数字是程序找到的最后一个.
我在实现GUI时将其包含在按钮actionlistener上,通过按下按钮,将上面显示的输出追加到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();
}
}
});
我本来是想使用收集器来计算平均值,但实际上我不知道如何实现…
任何帮助表示赞赏!
提前致谢!
解决方法:
我喜欢做这种事情的方法是使用地图和列表.
要读取文件中的行,我喜欢nio的读取方式,所以我会
List<String> lines = Files.readAllLines(Paths.get("RegistroVoti.txt"));
然后,您可以制作HashMap< String,List< Integer>> ;,该文件将存储每个人的姓名和与他们相关的号码的列表:
HashMap<String, List<Integer>> studentMarks = new HashMap<>();
然后,对每个循环使用a,遍历每一行并将每个数字添加到哈希图中:
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循环来在早期版本中对其进行计算)
有关我已使用的某些东西的更多信息,请参见:
> String#split()
> HashMap
> ArrayList
> Stream<T>#mapToInt()
希望这可以帮助!
编辑完整的解决方案:
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();
}
}
});
内容总结
以上是互联网集市为您收集整理的java-从.txt文件中获取的学生列表中的计算平均值全部内容,希望文章能够帮你解决java-从.txt文件中获取的学生列表中的计算平均值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。