【发布时间】:2015-11-28 23:14:18
【问题描述】:
有什么方法可以在每次使用累加器后将其设置为 0,然后它仍然执行相同的功能?或如何计算 Map 中每个键的整体值,如下所示:String、Hashmap String、Integer?我试图尽可能澄清,但我对此一无所知。
/*EXAMPLE OF HASHMAP: String e.g - UK ; America ; Africa , etc. String e.g - black , white, asian Integer e.g- 2008 , 103432 , 2391 // for every country the values are diff
*/
//one way to think of this is maybe with accumulator
// THIS IS AN EXAMPLE CODE WHICH DOES NOTHING.
int acc = 0 ;
for ( int i = 0 ; i < 20 ; i++ ) {
if ( i == 1 ) {
acc++; } // after acc ++ and it is 1, I want it to be again 0;
if ( i == 3 ) {
acc++; } // so that on this stage it will be 1
}
//Another alternative way may be:
Map<String,HashMap<String,Integer>> question = new HashMap<>();
int count = 0 ;
for(String regions : question.keySet())
{
for (String people : question.get(regions).keySet())
{
count = count + question.get(regions).get(people); // and here it will count all the value but I want to count it for each region and then become to 0 again, so that I can have the overall value for each of the people(keys)
}
}
【问题讨论】:
-
...不明白你的意思。您可以在使用它执行任何功能之后只
acc = 0吗?请澄清您的查询。您确定不想在循环中包含第二个if吗?因为您当前的代码中不包括在内。而且循环没有意义。也许如果你能指定你想要完成的事情和问题,你可能会得到更好的帮助。 -
如果你想让 act 保持在 0 那么增加它有什么意义呢?
-
你忘记打开 { 括号 for 循环和右括号 } 因此我超出范围
-
这里我没有给出具体的代码,而是一个示例。关键是计算 HashMap 中一个键的多个值(在我的情况下),然后移动到下一个键并再次计数,以便我拥有每个键的整体整数值。
-
你的 hashmap 是什么样子的?
标签: java hashmap accumulator