First of all I must apologies for I am uncertain how to word my title well.
However the problem I am facing is a continuation of another question that brought me one step closer to completing this particular program. Onto the problem though.
Here is my current output:
Income
{Jack=46, Mike=52, Joe=191}
These are inside the HashMap and I printed that out, what I need to do though is make this output more presentable and I guess that leads to needing to manipulate/get certain Data from inside the Map and then make it presentable.
The goal I am aiming for is to get my output to look like this:
Jack: $191
Mike: $52
Joe: $46
I'm still very new to Java and programming in general so I'm just wondering if this is possible or if I have tackled this all from the wrong way in the beginning?
Below is my code:
public static void main(String[] args) {
String name;
int leftNum, rightNum;
//Scan the text file
Scanner scan = new Scanner(Test3.class.getResourceAsStream("pay.txt"));
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);
}
}
System.out.println("Income");
System.out.println(nameSumMap); //print out names and total next to them
//output looks like this ---> {Jack=46, Mike=52, Joe=191}
//the next problem is how do I get those names on seperate lines
//and the total next to those names have the symbol $ next to them.
//Also is it possible to change = into :
//I need my output to look like below
/*
Jack: $191
Mike: $52
Joe: $46
*/
}
}
Well instead of relying on the default toString()
implementation of HashMap
, just loop over the entries:
for (Map.Entry<String, Long> entry : nameSumMap.entrySet()) {
System.out.println(entry.getKey() + ": $" + entry.getValue());
}
See more on this question at Stackoverflow