【问题标题】:Math.random won't randomize number 9 whenever it has to be assigned to last array slot每当必须将数字 9 分配给最后一个数组槽时,Math.random 都不会随机化
【发布时间】: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; - 请仔细阅读。
  • 谢谢我的朋友!

标签: java arrays random


【解决方案1】:

您的a[i] = (int)(Math.random()*9) + 0; 行与您在上面使用 Math.random() 的时间不同。上面你说(int)(Math.random()*9) + 1,这会给你一个[1,9]范围内的随机数。

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

【讨论】:

  • 谢谢我的朋友!
  • 不客气!如果它解决了您的问题,请随时接受此答案。
猜你喜欢
  • 2020-10-12
  • 2016-09-29
  • 1970-01-01
  • 2019-04-15
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 1970-01-01
相关资源
最近更新 更多