首先,我必须道歉,因为我不确定如何正确表达我的标题。
然而,我面临的问题是另一个问题的延续,它使我离完成这个特定的程序又近了一步。但还是要解决这个问题。
这是我当前的输出:
Income
{Jack=46, Mike=52, Joe=191}
这些位于 HashMap 内部,我将其打印出来,但我需要做的是使此输出更美观,我猜这会导致需要从 Map 内部操作/获取某些数据,然后使其易于呈现。
我的目标是让我的输出看起来像这样:
Jack: $191
Mike: $52
Joe: $46
我对 Java 和编程还很陌生,所以我只是想知道这是否可能,或者我是否从一开始就以错误的方式解决了这一切?
下面是我的代码:
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
*/
}
}
最佳答案
好吧,不要依赖 HashMap
的默认 toString()
实现,只需循环遍历条目即可:
for (Map.Entry<String, Long> entry : nameSumMap.entrySet()) {
System.out.println(entry.getKey() + ": $" + entry.getValue());
}
关于java - 从 HashMap 中获取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31303191/