简体   繁体   中英

Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.HashMap.get(Object)" is null

when I am trying to compare values of character(keys) using string in a Hashmap

for(int i = 0 ; i < s.length()-1 ; i++){

                if(map.get(s.charAt(i)) <= map.get(s.charAt(i+1))){
                    sum = sum+map.get(s.charAt(i));
                }
                else{
                    sum = sum + map.get(s.charAt(i+1)) - map.get(s.charAt(i));
                }
            }

can anybody help me out?

If the value of map is Integer,you can use below code to avoid it

for(int i = 0 ; i < s.length()-1 ; i++){

    Integer a = map.get(s.charAt(i));
    Integer b = map.get(s.charAt(i+1))
    if(a!=null && b!=null){
        if(a<=b){
        sum = sum+a;
        }
        else{
            sum = sum + b - a;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM