I have been trying to tackle this problem for a fair few days now and I have only managed to solve half of it, the next part that is troubling me seems to be a little more challenging and was wondering if I could be pointed in the right direction as to how I can tackle it.
I have 3 names that keep re-occurring in a text file on each line (in a random order) and with each of those names 2 numbers next to them that represent Price and Quantity. (As shown below)
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
I have managed to multiply those 2 numbers on each line for my answer next to each name. (First problem solved)
The next part I am having difficulty tackling, is how I am going to add together all the numbers next to each of the 3 individual names that appear into a total.
I have pondered whether I should use Switch, While, if, else loops and/or arrays but I can't seem to get my head around how to achieve my desired result. I have started to doubt whether or not my current code (Shown below) has gone a step in the wrong direction for getting the total income of the 3 names.
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
My latest thoughts were pondering the use of an if, if else loop but I can't seem to think of a way to get Java to read a name and get the number next to it. Then find all lines with the same name for its number, finally adding all the numbers next to that persons name. Repeat for the 3 names.
My apologies if I've made this seem more complicated than it may be but I've gotten quite lost recently and feel I've hit another brick wall.
What about a
Map<String, Long>
:At the end, the map contains the sum associated with each name.