【问题标题】:Java scanning file and printing word (with multiple instances) onceJava扫描文件和打印word(有多个实例)一次
【发布时间】:2015-01-08 16:13:44
【问题描述】:

我有一个程序可以扫描包含足球比分的文件,例如:

Leeds : 1 : Manchester City : 2
Manchester City : 3 : Chelsea : 1

我目前正在逐行扫描它,然后通过 : 将其拆分。但是我想创建一个团队的打印而不重复它 即

Manchester City total goals = 5
Chelsea total goals = 1
Leeds City total goals = 1

有没有一种方法可以做到这一点,而无需对团队名称进行硬编码。所以它只是扫描一个文件并选择团队,但只选择一次。分数在这里并不重要,我只是以他们为例,团队名称是我想要清楚地打印出来的。

我试过了:

    While (file.hasNext()){
    String line = file.nextLine();
    String[] word = line.split(":");
    System.out.println(teamname+" total goals ="+goals );
    }

【问题讨论】:

    标签: java file printing


    【解决方案1】:

    与其打印目标,不如立即将它们存储在地图中:

    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);
        }
    }
    

    打印总数:

    for (Map.Entry<String, Integer> teamGoalsEntry : goalCounts.entrySet()) {
        System.out.println(teamGoalsEntry.getKey() + " total goals=" + teamGoalsEntry.getValue());
    }
    

    您也可以使用 AtomicInteger 来更新目标,而不是覆盖 Map 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 2015-02-13
      • 2016-01-10
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多