【发布时间】:2016-03-16 03:14:04
【问题描述】:
我的代码创建了一个大小为 10 的数组,它从 0 到 9 随机数字以适合每个插槽。当直到最后一个空格才选择数字 9 时,问题就出现了。 Math.random 不断随机化数字,但它永远不会选择数字 9。我运行该程序大约 1 分钟,它从未选择它。
这是我的程序
public class GenerateRandomNumbers{
// main method
public static void main(String[] args) {
int aSize = 10;
int[] a = new int[aSize];//setting size of array
for(int i = 0; a.length > i; i++){//looping through the whole array
a[i] = (int)(Math.random()*9) + 1;//assigning random number to each slot of array
System.out.println("assign " + a[i] + " to i" + i);
//looping through filled array slots.
for(int k = i-1; -1 < k; k--){
System.out.println("Check if " + a[i] + " i"+ i + " = " + a[k]+ " k"+ k );
//if not unique give a new number
if(a[i] == a[k]){
System.out.println("CHANGE HERE");
a[i] = (int)(Math.random()*9) + 0;
System.out.println("assign " + a[i] + " to " + i);
k = i;//reset loop so it checks all over again
}
}
System.out.println("ACCEPT");
}
for(int i = 0; a.length > i; i++){
System.out.println(a[i]);
}
}
}
谁能解释一下是什么导致了这个错误?
【问题讨论】:
-
a[i] = (int)(Math.random()*9) + 0;- 请仔细阅读。 -
谢谢我的朋友!