找不到intValue方法

时间:2013-06-13 15:36:26

标签: java

I have made a programme to count the number of words using HashMap.Here it is-:


import java.util.*;
class Count{
    public static void main(String args[]){
        Scanner s=new Scanner(System.in);
        String in=s.nextLine();
        HashMap hm=new HashMap();
        String sh[]=in.split(" ");
        for(int i=0;i<sh.length;i++){
            String key=sh[i];
            if(sh[i].length() > 1){
                if(hm .get(key)==null){
                    hm.put(key,i);
                }
                else{
                    int value=new Integer(hm.get(key).intValue());
                    value++;
                    hm.put(key,value);
                }
            }
        }
        System.out.println(hm);
    }
}

但是在这个程序中我得到的错误是.intValue()符号没有找到,因为我使用的是jdk 1.6自动装箱和拆箱的功能被添加所以我猜这是问题。我想计算计数所以请给我的解决方案。

3 个答案:

答案 0 :(得分:2)

你应该写这段代码。

int value=new Integer((Integer)hm.get(key)).intValue();

或更好

int value = (Integer)hm.get(key);

答案 1 :(得分:1)

参数化地图:使用HashMap<String, Integer>代替HashMap

HashMap<String, Integer> hm = new HashMap<String, Integer>();

这样您就不需要将map值转换为int。它会自动“转换”:

int value= hm.get(key);
value++;
hm.put(key,value);

通常,您不会将变量声明为HashMap之类的具体实现,而是使用泛型Map接口:

Map<String, Integer> hm = new HashMap<String, Integer>();

答案 2 :(得分:0)

所以你有HashMap没有指定里面存储的对象类型 要指定内部存储的内容,您需要使用泛型 将hashmap定义为HashMap<String,Integer> hm = new HashMap<String,Integer>();
否则,内部存储的所有内容都将被视为ObjectObject没有intValue方法。所以编译器会抛出错误。