我正在尝试打印一个特定键在一个数组中出现的次数,并且它似乎正在为所有值打印一个。任何人都可以告诉我我在下面的代码中遇到了什么逻辑错误:
import java.util.HashMap;
import java.util.Map;
public class MostOccuranceOfNumber {
public static void main(String[] args) {
int[] n = {1,2,3,4,5,6,7,7,7,7};
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
// Create Hash Map
for(int i = 0 ; i < n.length ; i++){
if(map.containsKey(n)){
map.put(n[i], map.get(n[i]) +1);
}
else{
map.put(n[i], 1);
}
for(Map.Entry<Integer, Integer> m : map.entrySet()){
System.out.println("Key "+m.getKey()+"Occured"+m.getValue()+"times");
}
}
}
}
答案 0 :(得分:1)
试试这个:
import java.util.HashMap;
import java.util.Map;
public class MostOccuranceOfNumber {
public static void main(String[] args) {
int[] n = {1,2,3,4,5,6,7,7,7,7};
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
// Create Hash Map
for(int i = 0 ; i < n.length ; i++){
if(map.containsKey(n[i])){//you made mistake here
map.put(n[i], map.get(n[i]) +1);
}
else{
map.put(n[i], 1);
}
}
}
for(Map.Entry<Integer, Integer> m : map.entrySet()){
System.out.println("Key "+m.getKey()+"Occured "+m.getValue()+" times ");//Sorry forgot to take it outside
}
}