当前位置: 代码迷 >> J2SE >> 这个程序错哪了?使用Map判断某个字符数组中重复出现的字符数
  详细解决方案

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

热度:55   发布时间:2016-04-24 01:18:47.0
这个程序哪里错了?使用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);     }}
  相关解决方案