java - 查找文本文件中 3 个重复出现的姓名(人)的总收入

标签 java arrays loops switch-statement

我已经尝试解决这个问题好几天了,但我只解决了一半,困扰我的下一部分似乎更具挑战性,想知道是否可以指出我关于如何解决这个问题的正确方向。

我有 3 个名称,它们在文本文件的每一行中不断重复出现(以随机顺序),并且每个名称旁边都有 2 个数字,分别代表价格和数量。 (如下图)

Jack 8 2
Joe 4 2
Mike 14 5
Jack 3 3
Jack 9 1
Jack 2 2
Mike 20 6
Sofia 11 3
Jack 13 6
Mike 8 5
Joe 8 4
Sofia 8 1
Sofia 1 6
Sofia 9 4
  • 我已经设法将每行上的这 2 个数字相乘,作为每个名字旁边的答案。 (第一个问题解决了)

  • 我遇到困难的下一部分是如何将出现的 3 个个人姓名旁边的所有数字加在一起,形成总数。

我考虑过是否应该使用 Switch、While、if、else 循环和/或数组,但我似乎不知道如何实现我想要的结果。我开始怀疑我当前的代码(如下所示)在获取 3 个名称的总收入方面是否朝着错误的方向迈出了一步。

String name;
int leftNum, rightNum;

//Scan the text file
Scanner scan = new Scanner(Explore.class.getResourceAsStream("pay.txt"));

while (scan.hasNext()) { //finds next line
  name = scan.next(); //find the name on the line
  leftNum = scan.nextInt(); //get price
  rightNum = scan.nextInt(); //get quantity
  int ans = leftNum * rightNum; //Multiply Price and Quanity
  System.out.println(name + " : " + ans);
}

// if name is Jack,
//  get that number next to his name
//  and all the numbers next to name Jack are added together
// get total of the numbers added together for Jack

// if else name is Mike,
// Do the same steps as above for Jack and find total

// if else name is Joe,
// same as above and find total

我最近的想法是考虑使用 if, if else 循环,但我似乎想不出一种方法让 Java 读取名称并获取其旁边的数字。然后找到其号码具有相同名称的所有行,最后添加该人姓名旁边的所有号码。对 3 个名称重复上述操作。

如果我让这件事看起来比实际情况更复杂,我很抱歉,但我最近迷失了方向,感觉自己又碰上了另一堵墙。

最佳答案

Map<String, Long> 怎么样? :

Map<String, Long> nameSumMap = new HashMap<>(3);
while (scan.hasNext()) {       //finds next line
    name = scan.next();        //find the name on the line
    leftNum = scan.nextInt();  //get price
    rightNum = scan.nextInt(); //get quantity

    Long sum = nameSumMap.get(name);
    if(sum == null) {          // first time we see "name"
        nameSumMap.put(name, Long.valueOf(leftNum + rightNum));
    } else {
        nameSumMap.put(name, sum + leftNum + rightNum);
    }
}

最后, map 包含与每个名称关联的总和。

关于java - 查找文本文件中 3 个重复出现的姓名(人)的总收入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30804965/

相关文章:

java - JMS 有哪些替代方案?

java - Swing 中的 GridBagLayout 格式设置

arrays - swift 2 : Extra argument in call for array and struct

node.js - Node JS 如何处理缓慢的 http 请求?

loops - 在 SAS `X` 命令中,如何传递回车符?

java - 如何从Android Wear进行Socket连接并向服务器发送数据

java - 如何在策略文件中设置java.awt.awtpermission?

arrays - 数组仅包含最后添加的值但计数仍然相同

python - 在包含数组元素的数据帧上应用 numpy 运算和向量索引的自然方法

java - 我的循环有些东西不工作。它可以运行但不循环