即使密钥存在,HashMap get方法也返回null

时间:2018-03-25 10:23:44

标签: java hashmap

我有以下代码,如下所示。我的代码中的HashMap适用于第一次迭代,但是对于第二次迭代,它返回null。当密钥已经存在时,为什么会发生这种情况。 我的代码是:

import java.util.*;
import java.io.*;

class Main {    
    public static void main(String[] args) throws IOException{

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while((str=br.readLine())!=null && str.length()!=0){
            int noOfPeople = Integer.parseInt(str);
            String names[] = br.readLine().split(" ");

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

            for(int i =0;i < noOfPeople; i++){
                cost.put(names[i], 0);
            }

            for(int i = 0; i < noOfPeople; i++){
                String info[] = br.readLine().split(" ");

                cost.put(info[0], cost.get(info[0]) - Integer.parseInt(info[1]));

                int giftsGiven = Integer.parseInt(info[2]);
                for(int j = 0; j < giftsGiven; j++){
                    cost.put(info[3+j], cost.get(info[3+j]  + Integer.parseInt(info[1])/noOfPeople));
                }
            }

            for(int i = 0; i < noOfPeople; i++){
                System.out.println(names[i] + " "+cost.get(names[i]));
            }
        }
    }
}

输入是:

5

dave laura owen vick amr

dave 200 3 laura owen vick

owen 500 1 dave

amr 150 2 vick owen

laura 0 2 amr vick

vick 0 0

1 个答案:

答案 0 :(得分:0)

您正试图从地图中get错误key

您应该按键info[3+j]获取,并根据拥有者添加新的礼物数量:

cost.put(info[3+j], cost.get(info[3+j]) + (Integer.parseInt(info[1])/noOfPeople));

并且,最好在除法之前确保noOfPeople不为零,否则程序可能会崩溃。