问题遇到的现象和发生背景
//随机生成10000个整数,表示10000个学生的数学成绩,范围设定0-100分.
// 编写程序,统计每个分值的人数,
// 例如,得0分的人有40人,得87分的有2398人.
问题相关代码,请勿粘贴截图
package Text5;
import java.util.;
//import java.lang.;
//随机生成10000个整数,表示10000个学生的数学成绩,范围设定0-100分.
// 编写程序,统计每个分值的人数,
// 例如,得0分的人有40人,得87分的有2398人.
public class colection {
public static void main(String [] args)
{
Collection collection = new ArrayList();
Random rad = new Random();
//1 随机生成10000个整数,表示10000个学生的数学成绩,范围设定0-100分
while ( collection.size()<10000 )
{
collection.add( rad.nextInt(100) );
}
//2 编写程序,统计每个分值的人数,
HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();
Iterator iterator = collection.iterator();
while ( iterator.hasNext())
{
if( hashMap.get((Integer) iterator.next()) == null )
{
hashMap.put((Integer) iterator.next(),(Integer)1);
}
else
{
System.out.println( hashMap.get((Integer) iterator.next()));
// hashMap.get((Integer) iterator.next());
hashMap.replace((Integer) iterator.next(), hashMap.get((Integer) iterator.next())+1);
}
}
System.out.println(hashMap.size());
}
}
有问题是代码是
hashMap.replace((Integer) iterator.next(), hashMap.get((Integer) iterator.next())+1)
运行结果及报错内容
Exception in thread "main" java.lang.NullPointerException
at Text5.colection.main(colection.java:39)
我的解答思路和尝试过的方法
我调试了一会,发现如果输出System.out.println( hashMap.get((Integer) iterator.next())他有时候会是空值
可是我明明在前面已经判断了然后给他赋值了呀。
我想要达到的结果
希望大家能帮一下我,谢谢