每当必须将数字 9 分配给最后一个数组插槽时,Math.random 都不会随机化数字 9



我的代码创建了一个大小为 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;与你上面使用Math.random()的时间不同。上面你说(int)(Math.random()*9) + 1,那会给你一个 [1,9] 范围内的随机数。

(int)(Math.random()*9) + 0永远不会计算为 9,其范围为 [0,8]。

最新更新