当我的 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/