无法在 java 中使用枚举遍历哈希表



这是我尝试打印密钥的代码,但它从未被执行,而是只转到最后一行并抛出空指针异常。

Enumeration<String> keys = states.keys();
        int max=0;
        String maxClass="";
        while(keys.hasMoreElements())
        {
            String key = keys.nextElement();
            System.out.println(key);
                if(states.get(key)>=max)
                {
                    max=states.get(key);
                    maxClass=key;
                }
                System.out.println(maxClass);
        }
        System.out.println(maxClass);
        Category c = classes.get(maxClass);
        c.add(p);

这是分类函数的完整代码。

static void classify(ArrayList<Point> cities,Hashtable<String,Category> classes)
{
    for(Point p: cities)
     {
        ArrayList<Point> nbours = new ArrayList<Point>();
        nbours.addAll(getNbours( p,cities));
        // System.out.println(p.city);
        Hashtable<String,Integer> states = new  Hashtable<String,Integer>();
        for(Point pt : nbours)
        {
                //System.out.println(pt.city);
                if(states.containsKey(pt.state))
                {
                    int cnt = states.get(pt.state) + 1;
                    states.remove(pt.state);
                    states.put(pt.state,cnt);
                    //states.add(state,);
                }
                else
                {
                    states.put(pt.state,1);
                }
                //System.out.println(states.get(pt.state));
        }
        Enumeration<String> keys = states.keys();
        int max=0;
        String maxClass="";
        System.out.println(keys);
        while(keys.hasMoreElements())
        {
            String key = keys.nextElement();
            System.out.println(key);
                if(states.get(key)>=max)
                {
                    max=states.get(key);
                    maxClass=key;
                }
                System.out.println(maxClass);
        }
        System.out.println(maxClass);
        Category c = classes.get(maxClass);
        c.add(p);
        System.out.println(p.city+ "Classified");
        nbours.clear();
    }

如果执行到达最后一行并且与 NullPointerException 一起存在,则 "c" 为 null。这意味着调用Category c = classes.get(maxClass);返回 null。检查 maxClass 中的键在类对象中是否可用。

最新更新