[英]Java scanning file and printing word (with multiple instances) once
I have a program which scans through a file containing football scores such as: 我有一个程序可以扫描包含足球得分的文件,例如:
Leeds : 1 : Manchester City : 2
Manchester City : 3 : Chelsea : 1
I am currently scanning it by lines and then splitting it up via the :. 我目前正在按行对其进行扫描,然后通过:进行拆分。 However I want to create a print out of a team without repeating it ie
但是我想创建一个团队的打印而不重复
Manchester City total goals = 5
Chelsea total goals = 1
Leeds City total goals = 1
is there a way I can I can do this without hard coding what the teamname is. 有没有办法我可以不用硬编码团队名称是什么办法。 so it just scans through a file and selects the teams but only once.
因此它只扫描文件并选择团队,但仅一次。 The scores are not important here Im just using them as an example the teamnames are what I want to to distinctly print.
分数并不重要,我只是以分数为例,而我要清楚地打印出队名。
I tried: 我试过了:
While (file.hasNext()){
String line = file.nextLine();
String[] word = line.split(":");
System.out.println(teamname+" total goals ="+goals );
}
Instead of printing the goals immediately store them in a Map: 无需打印目标,而是立即将它们存储在地图中:
private Map<String, Integer> goalCounts = new HashMap<>();
private void addGoals(String teamName, int numGoals) {
if (goalCounts.containsKey(teamName)) {
goalCounts.put(teamName, goalCounts.get(teamName) + numGoals);
}
else {
goalCounts.put(teamName, numGoals);
}
}
To print out the totals: 要打印总计:
for (Map.Entry<String, Integer> teamGoalsEntry : goalCounts.entrySet()) {
System.out.println(teamGoalsEntry.getKey() + " total goals=" + teamGoalsEntry.getValue());
}
You could alternatively use an AtomicInteger to update the goals instead of overwriting the Map value. 您也可以使用AtomicInteger来更新目标,而不是覆盖Map值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.