我试图实现一个简单的树形图来计算整数的出现次数,但它给了我一个NullPointerException
并且我不知道如何修复它。
Exception in thread "main" java.lang.NullPointerException
at exercises.CountOccurances_20_07.main(CountOccurances_20_07.java:21)
这是代码:
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class CountOccurances_20_07
{
public static void main(String[] args)
{
int[] list = {2, 3, 40, 3, 5, 4, 3, 3, 3, 2, 0};
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
for(int i: list)
{
int key = list[i];
if(list.length > 1)
{
if(map.get(key) == 0)
{
map.put(key, 1);
}
else
{
int value = map.get(key).intValue(); // line 21
value ++;
map.put(key, value);
}
}
}
//get all entries into set
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
//get key and value from entry set
for(Map.Entry<Integer, Integer> entry: entrySet)
System.out.println(entry.getValue() + "\t" + entry.getKey());
}
}