您好,我在随机抽取中遇到了重复。我尝试在表上执行此操作,但每次将生成的随机数与表中的数字进行比较时都会遇到问题。请小心,因为此代码现在是无限循环,会引发 ArrayIndexOutOfBoundsException。你有什么想法?向你展示我想要得到的东西类似于波兰电视节目 Lotto,他们在球上抽取 6 个随机数字,不重复。 我已经看到主题是在列表上完成的,但是可以在这样的表格上吗?
public static void main(String[] args) {
Lotto lot = new Lotto();
int[] table = new int[6];
Random random = new Random();
for(int i = 0; i < 6; i++) {
int numbers = random.nextInt(48) + 1;
for(int k = 0; k < 6; k++) {
if (table[k] != numbers) {
try {
table[i] = numbers;
} catch (ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
} else {
i--;
}
}
}
Arrays.sort(table);
for (int m = 0; m < 6; m++) {
System.out.println(table[m]);
}
}
最佳答案
我建议采用以下方法:
// Get list of all number
List<Integer> all = new ArrayList<>();
for (int i = 1; i <= 48; i++) {
all.add(i);
}
//Shuffle it
Collections.shuffle(all);
//Take first 6
List<Integer> result = all.subList(0, 6);
关于java - 在 table/java 上绘制六个不重复的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605941/