【发布时间】:2015-09-26 23:38:02
【问题描述】:
首先我必须道歉,因为我不确定如何用好我的标题。
但是,我面临的问题是另一个问题的延续,它使我离完成这个特定程序更近了一步。解决问题。
这是我当前的输出:
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
*/
}
}
【问题讨论】:
-
您是否要打印所有按值排序的地图条目?
标签: java dictionary hash hashmap output