这是我目前的情况
int[] question = new int[25];
for (int i = 0; i < question.length; i++){
question[i] = i+1;
}
Random rand = new Random();
int max = question.length-1, min = 1;
for(int i = 0; i < question.length; i++){
int idx = rand.nextInt((max - min) + 1) + min;
randg[i] = idx;
question[i] ^= question[idx];
question[idx] ^= question[i];
question[i] ^= question[idx];
if(question[i] == 0){
System.out.println("Something went wrong!" + i + " " + idx);
}
}
所以问题似乎是当 rand 值 (idx) 等于 i 时,对于交换...它只是将值替换为 0。
我该如何解决这个问题?
最佳答案
我知道的最快的修复;使用 Integer[]
, Arrays.asList(T...)
和 Collections.shuffle(List)
喜欢
Integer[] question = new Integer[25];
for (int i = 0; i < question.length; i++) {
question[i] = i + 1;
}
System.out.println(Arrays.toString(question));
Collections.shuffle(Arrays.asList(question));
System.out.println(Arrays.toString(question));
或者,您可以使用您的代码添加
for(int i = 0; i < question.length; i++){
int idx = rand.nextInt((max - min) + 1) + min;
if (idx == i) {
i--;
continue;
}
关于java - 在 Java 中改组数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236856/