【发布时间】:2014-09-05 17:52:10
【问题描述】:
我的任务是对类别列表进行排序。一份购物清单,如果你愿意的话。这些类别是来自用户的输入,要购买的物品。在输入相关类别的字符串名称后(当然使用扫描仪),用户可以输入该类别的数量(整数),然后输入该类别的单位成本(双精度)。 系统会提示他们重复此操作,直到他们命名的类别为“结束”。
这一切都很好,而且我已经编写了代码来获取所有这些信息,并找到并打印出最大成本项目、最大数量项目和其他信息。我需要帮助的是我的重复类别。例如,假设用户输入“cars”,后跟一个整数 3,然后是数字 24000.00。然后他们放入“refigerators”,然后是 1,然后是 1300.00。然后用户输入第一个条目的副本,即“汽车”,后跟整数 5,然后是双精度 37000.00。如何让我的代码重新访问旧条目,将新数量添加到旧条目中,并在不覆盖旧条目的情况下存储该值?我还需要找到列表中项目的最大平均成本。我是 HashMap 的新手,所以我在代码中苦苦挣扎://创建一个 arrayList 来存储值
// create an arrayList to store values
ArrayList<String> listOne = new ArrayList<String>();
listOne.add("+ 1 item");
listOne.add("+ 1 item");
listOne.add("+ 1 item");
// create list two and store values
ArrayList<String> listTwo = new ArrayList<String>();
listTwo.add("+1 item");
listTwo.add("+1 item");
// put values into map
multiMap.put("some sort of user input detailing the name of the item", listOne);
multiMap.put("some other input detailing the name of the next item", listTwo);
// i need the user to input items until they type "end"
// Get a set of the entries
Set<Entry<String, ArrayList<String>>> setMap = multiMap.entrySet();
// time for an iterator
Iterator<Entry<String, ArrayList<String>>> iteratorMap = setMap.iterator();
System.out.println("\nHashMap with Multiple Values");
// display all the elements
while(iteratorMap.hasNext()) {
Map.Entry<String, ArrayList<String>> entry =
(Map.Entry<String, ArrayList<String>>) iteratorMap.next();
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println("Key = '" + key + "' has values: " + values);
}
// all that up there gives me this:
具有多个值的 HashMap Key = 'some other input detailing the name of the next item' 具有值:[+1 项,+1 项] Key = '某种详细说明项目名称的用户输入' 具有值:[+ 1 项,+ 1 项,+ 1 项]
但我没有给用户输入物品数量或成本的机会……我迷路了。
【问题讨论】:
-
Set 仅存储唯一值,因此当您从 multiMap.entrySet 获取 setMap 时会出现问题。因为你有相同的价值,它们只会被存储一次......
-
“我还需要找到最大的平均成本”是什么意思?什么的平均值?
-
这意味着如果我有:鸡蛋 1 7.00,牛奶 1 1.99,鸡蛋 2 2.50,那么程序应该打印出鸡蛋具有最大的平均成本项目:即 (7+5)/ 3 = 4
-
我的答案中的示例代码是否解决了您正在查看的问题?