Java Math.random不会在必须将数字9分配给最后一个数组插槽时将其随机化
我的代码创建了一个大小为10的数组,它将0到9之间的数字随机分配到每个插槽中。当数字9直到最后一个空格才被选中时,问题就出现了。Math.random保持随机数字,但它永远不会选择数字9。我运行了大约1分钟的程序,但它没有选择它 这是我的节目Java Math.random不会在必须将数字9分配给最后一个数组插槽时将其随机化,java,arrays,random,Java,Arrays,Random,我的代码创建了一个大小为10的数组,它将0到9之间的数字随机分配到每个插槽中。当数字9直到最后一个空格才被选中时,问题就出现了。Math.random保持随机数字,但它永远不会选择数字9。我运行了大约1分钟的程序,但它没有选择它 这是我的节目 public class GenerateRandomNumbers{ // main method public static void main(String[] args) { int aSize = 10;
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]=intMath.random*9+0;与您使用上面的Math.random时不同。上面你说的是intMath.random*9+1,这会给你一个[1,9]范围内的随机数
intMath.random*9+0永远不会计算为9,其范围为[0,8]。a[i]=intMath.random*9+0;-仔细阅读。谢谢我的朋友!谢谢我的朋友!不客气!如果这个答案解决了你的问题,请随意接受。