题目:
准备一个 HashMap 集合,统计字符串"123,456,789,123,456"中每个数字字符串出现的次数并打印出来。
如:
123 出现了 2 次
456 出现了 2 次
789 出现了 1 次
package com.lagou.model03;
import java.util.HashMap;
public class HashMapCount {
public static void main(String[] args) {
String string = "123,456,789,123,456";
HashMap<Integer, String> hashMap = new HashMap<>();
int m = 0;
int n;
for (int i = 0, j = 0;i <= string.length() - "456".length();i += 4,j++)
{
hashMap.put(j, string.substring(i, i + 3));
m = j;
}
System.out.println(hashMap); // 测试代码
for (int i = 0;i <= m;i++)
{
n = 1;
for (int j = i + 1;j <= m;j++)
{
if (hashMap.get(i).equals(hashMap.get(j)))
{
n++;
hashMap.remove(j);
}
}
System.out.println(hashMap); // 测试代码
System.out.println(hashMap.get(i) + "出现了" + n + "次");
}
}
}
请问这个空指针异常应该怎么处理呢?