Java-随机数生成器中的漏洞
我正在创建一个程序,该程序应该随机指定我将在Java期中考试中解决的问题。 我创建了一个运行100000次的程序,并将每个问题作为键输入hashmap, 而其值是100000中生成的计数数。 我创建了以下简单程序:Java-随机数生成器中的漏洞,java,random,hashmap,Java,Random,Hashmap,我正在创建一个程序,该程序应该随机指定我将在Java期中考试中解决的问题。 我创建了一个运行100000次的程序,并将每个问题作为键输入hashmap, 而其值是100000中生成的计数数。 我创建了以下简单程序: public class randomChoice { public static Map<Integer, Integer> dictionary = new HashMap<Integer, Integer>(); public stat
public class randomChoice {
public static Map<Integer, Integer> dictionary = new HashMap<Integer, Integer>();
public static void randInt() {
Random rand = new Random();
int randomNum = rand.nextInt((33 - 1) + 1) + 1;
if (dictionary.containsKey(randomNum)) {
dictionary.put(randomNum, dictionary.get(randomNum) + 1);
} else {
dictionary.put(randomNum, 0);
}
}
public static void main(String[] args) {
int i = 0;
while (i < 100000) {
randInt();
i++;
}
System.out.println(dictionary);
Map.Entry<Integer, Integer> maxEntry = null;
for (Map.Entry<Integer, Integer> entry : dictionary.entrySet()) {
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
System.out.println("\nThe question I will be using for the midterm is " + maxEntry.getKey() + " with a total count of " + maxEntry.getValue());
int total = 0;
for (Map.Entry<Integer, Integer> entry : dictionary.entrySet()) {
total = entry.getValue() + total;
}
System.out.println("\nTotal: " + total);
}
}
我的问题是,为什么总数是99967而不是100000?
看起来有点可疑,它正好短了33个,我有33个问题要挑。
我做错了什么?
我的缺陷在哪里?它可以帮助我创建100000个生成的随机数?因为当你第一次遇到33个地图条目中的每一个时,你放置了一个
0
,而不是1
。这是一个一错再错的错误
改变
dictionary.put(randomNum, 0);
到
dictionary.put(randomNum, 0);
dictionary.put(randomNum, 1);