- 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); }}