到目前为止我的代码:
public void lottoGame() {
HashSet<Integer> dups = new HashSet<Integer>();
for(int howMany = 1; howMany <= 6; howMany++) {
int lottoNumber = lottoNum.nextInt(49) + 1;
while(dups.contains(lottoNumber)) {
lottoNumber = lottoNum.nextInt(49) + 1;
}
dups.add(lottoNumber);
randomLotto[howMany] = lottoNumber;
System.out.println(lottoNumber);
}
for(int counter : dups) {
numberCount[counter]++; //to store the counting of random numbers
}
for(int counting = 1; counting < numberCount.length; counting++) {
System.out.println(counting + " occurs " + numberCount[counting] + " times");
}
}
基本上,我所做的是创建一个hashset并输入6个随机数。在我的最后2个for循环中,我试图计算我绘制哪个数字并打印出来的频率。问题是,无论出于何种原因,它在打印时从第3个字段开始。有谁知道为什么?
答案 0 :(得分:1)
以下是您提供的示例。我的输出是正确的。验证您可能未向我们展示的设置或其他代码。
请注意:Is there a limit on the maximum of number of lines which can be printed to console by BlueJ?
class Test
{
public void lottoGame()
{
int[] randomLotto = new int[50];
int[] numberCount = new int[50];
Random lottoNum = new Random();
HashSet<Integer> dups = new HashSet<Integer>();
for (int howMany = 1; howMany <= 6; howMany++)
{
int lottoNumber = lottoNum.nextInt(49) + 1;
while (dups.contains(lottoNumber))
{
lottoNumber = lottoNum.nextInt(49) + 1;
}
dups.add(lottoNumber);
randomLotto[howMany] = lottoNumber;
System.out.println(lottoNumber);
}
for (int counter : dups)
{
numberCount[counter]++; //to store the counting of random numbers
}
for (int counting = 1; counting < numberCount.length; counting++)
{
System.out.println(counting + " occurs " + numberCount[counting] + " times");
}
}
public static void main(String[] args)
{
new Test().lottoGame();
}
}
输出:
43
27
38
30
14
8
1 occurs 0 times
2 occurs 0 times
3 occurs 0 times
4 occurs 0 times
5 occurs 0 times
6 occurs 0 times
7 occurs 0 times
8 occurs 1 times
9 occurs 0 times
10 occurs 0 times
11 occurs 0 times
12 occurs 0 times
13 occurs 0 times
14 occurs 1 times
15 occurs 0 times
16 occurs 0 times
17 occurs 0 times
18 occurs 0 times
19 occurs 0 times
20 occurs 0 times
21 occurs 0 times
22 occurs 0 times
23 occurs 0 times
24 occurs 0 times
25 occurs 0 times
26 occurs 0 times
27 occurs 1 times
28 occurs 0 times
29 occurs 0 times
30 occurs 1 times
31 occurs 0 times
32 occurs 0 times
33 occurs 0 times
34 occurs 0 times
35 occurs 0 times
36 occurs 0 times
37 occurs 0 times
38 occurs 1 times
39 occurs 0 times
40 occurs 0 times
41 occurs 0 times
42 occurs 0 times
43 occurs 1 times
44 occurs 0 times
45 occurs 0 times
46 occurs 0 times
47 occurs 0 times
48 occurs 0 times
49 occurs 0 times
答案 1 :(得分:0)
我建议使用map,这个例子看起来更简单
public static void lotoGame() {
Random rand = new Random();
Map<Integer, Integer> loto = new HashMap<>();
while (loto.keySet().size() < 6) {
int lottoNumber = rand.nextInt(49) + 1;
loto.compute(lottoNumber, (key, value) -> value == null ? 1 : ++value);
}
loto.forEach((key,value)->{
System.out.println(key + " occurs " + value + " times");
});
}