java - HashMap 的简单方法似乎是正确的,但它不起作用

标签 java class oop methods hashmap

当我的 subscribedAnswers() 方法调用 countAnswers() 方法时,我收到 NullPointerException,但我检查了我的 HashMap 并且它包含正确的信息。我做错了什么?

if (database.get(i).equals('A'))

错误从 ^^ 开始

private int countA, countB, countC, countD; // counters for the different answers
HashMap<Integer, Character> database = new HashMap<Integer, Character>();

public void countAnswers() 
{
    while(!database.isEmpty())
    {
        for(int i = 0; i < database.size(); i++)
        {
            if (database.get(i).equals('A')) 
            {
                countA++;
            }
            if (database.get(i).equals('B'))
            {
                countB++;
            }
            if (database.get(i).equals('C')) 
            {
                countC++;
            }
            if(database.get(i).equals('D')) 
            {
                countD++;
            }
        }
    }
}
/*
 * checks if the student has submitted or not, if the student 
 * has then it removes the student and submits the new submittion, 
 * if not than just submits the student. then calls to counts the submitted answers
 */
public void sumbittedAnswers(int studentID, char answer) 
{

    if(database.containsKey(studentID))
    {
        database.remove(studentID);
        database.put(studentID, answer);
    }
    else
        database.put(studentID, answer);

    countAnswers();
}

最佳答案

HashMap 上的 get 不像数组那样工作。

database.get(i) 不是索引 i,它是获取 Object key。

因此,除非您的学生 ID 是 0,1,2,3,4 到 size-1,否则它将不起作用。

如果你想迭代 HashMap ,你需要这样做。

Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    System.out.println(pairs.getKey() + " = " + pairs.getValue());
}

关于java - HashMap 的简单方法似乎是正确的,但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26517713/

相关文章:

c++ - 那么现在 struct 可以有虚函数并支持继承吗?那么与 classes 有什么区别呢?信息隐藏的真正目的是什么?

C++ 如何让一个类依赖于一个命名空间,而那个命名空间又依赖于该类?

python - 关于 Python 'yield' 关键字的问题,我在其他地方没有找到答案,以及它在我正在处理的代码中的具体用途

每次都接受一个随机参数的 JavaScript 函数

java - 如何从具体子类中的重写方法访问通过抽象类中的构造函数实例化的对象的属性?

delphi - 隐藏仅在私有(private)协会中使用的成员的类?

c# - C# 中的匿名内部类?

Java模拟键盘

java - 将特定字符串替换为另一个字符串 - String#replaceAll()

java - 如何在java中表示无向加权图