日期:2014-05-20  浏览次数:20735 次

这个程序哪里错了?使用Map判断某个字符数组中重复出现的字符数?
Java code

import java.util.*;
public class ArgTest {
    public static void main(String[] args) {
        Map m = new HashMap();
        String[] arg = {"aaa","bbb","ccc","ddd","aaa","ccc","ccc"};
         for(int i = 0;i < arg.length;i++){
System.out.println("\n" + arg[i]);
            int num = (int) m.get(arg[i]);
            m.put(arg[i],(num == 0 ? 1 : num++));
        System.out.println(m);    
        }
    }
}



编译的时候没错,逻辑也没错,哪里错了呢?

Exception in thread "main" java.lang.NullPointerException
at ArgTest.main(ArgTest.java:8)


------解决方案--------------------
Java code

import java.util.*;
public class ArgTest {
    public static void main(String[] args) {
        Map<String,Integer> m = new HashMap<String,Integer>();
        String[] arg = {"aaa","bbb","ccc","ddd","aaa","ccc","ccc"};
         for(int i = 0;i < arg.length;i++){
             if(m.containsKey(arg[i])){
                 int temp = m.get(arg[i]);
                 m.remove(arg[i]);
                 m.put(arg[i], ++temp);
             }
             else{
                 m.put(arg[i],1);
             }
        }
         System.out.println(m); 
    }
}