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

Finding the total Income of 3 re-occurring names (people) in a text file

这几天我一直在努力解决这个问题,但只解决了一半,接下来困扰我的部分似乎更具挑战性,想知道我是否可以指出我如何解决它的正确方向。

我有 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

我考虑过是否应该使用 Switch、While、if、else 循环 and/or 数组,但我似乎无法理解如何实现我想要的结果。我开始怀疑我现在的代码(如下所示)是否在获取三个名字的总收入方面走错了一步。

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 个名字。

如果我让这看起来比实际情况更复杂,我深表歉意,但我最近迷路了,感觉又碰壁了。

您可以使用带有键 String(名称)和值 Double(花费的钱)的 Map。

每当你读到一行:

  1. 你用containsKey
  2. 检查名称是否在地图中
  3. 如果不存在,你put把当前金额给地图
  4. 否则,如果它存在,您可以使用 get 获取当前值,添加当前金额,然后 put 将结果返回到地图中。

你可以看看HashMap

您将创建其中的 2 个,一个用于数量,一个用于价格。当你第一次找到这个名字时,你就把价格放在那里。当您再次找到相同的名称时,只需将当前值与新值相加即可。

一种更面向对象的实现方式,可能如下所示:

  • 创建具有以下属性的对象:NamePriceQuantity
  • 当你浏览你的文件时,每行创建一个对象,表示每个人买了什么。
  • 创建对象后,将其添加到列表中。

这将允许您遍历对象并进行您可能需要的任何计算。

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

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