繁体   English   中英

为什么即使我编写的代码不会产生零或重复的数字,我的程序的输出也总是以两个连续的零开头?

[英]Why does the output for my program always start with two consecutive zeros even though I wrote a code that doesn't produce zeros or repeated numbers?

我正在尝试创建一种使用随机数生成器生成彩票号码的方法。 有两组数字。 第一组应该具有五个不同的数字,这些数字按排序顺序显示,范围为1至56。 第二组由范围为1到46的单个数字组成。 当我运行程序时,即使我试图以不允许组1包含零或重复数字的方式编写代码,组1总是以两个连续的零开始。 最初,我认为问题一定与随机数生成器有关,因此我尝试在NetBeans中调试项目。 当我逐步执行代码行时,我可以看到分配给n的值,n是保存由随机数发生器产生的数字的变量。 n的值是54、50、11、49和28。在程序中,n的值放入排序的数组中。 因此,第一组的输出应为11、28、49、50、54,但应为0、0、11、28、49。

这是我的代码:

 public static void MakeTickets(){

    int [] Group1= new int [5];

    int Group2;

    int n;

    Random rand= new Random ();

    for (int j=0 ; j<5; j++){
        //Here, I try to make sure that the range for n is 1-56

        n= rand.nextInt(55)+1;  

        //Here, I try to make sure that a number isn't put into the group one
        //array more than once

        while (Arrays.binarySearch(Group1, n)>=0){
            n= rand.nextInt(55)+1; 
        }


        Group1[j]=n;

        Arrays.sort(Group1);
    }

    Random r= new Random();

    int num= r.nextInt(45)+1;

    Group2=num;

    System.out.print("Here is your ticket: Group One= ");

    for(int number: Group1){
        if (number==Group1[4]){
        System.out.print(number);
        } else {
            System.out.print(number+", ");
        }
    }

    System.out.println(" Group Two= "+Group2);
}

这是输出:

Here is your ticket: Group One= 0, 0, 33, 45, 50 Group Two= 40

我尝试使用ThreadLocalRandom代替,但是我仍然遇到相同的问题。 有人知道我在做什么错吗? 任何和所有建议都将不胜感激。

Arrays.sort(Group1); 造成了问题。

我相信Arrays.sort(Group1); 应该放在第一个for循环之后(生成Group1值之后)。

当前,在将每个值相加后对值进行排序。

最初,数组中的0 0 0 0 0

第一次迭代

生成第一个数字后

n= rand.nextInt(55)+1; //lets assume the generated value is 43

的数组变成43 0 0 0 0

调用排序后,

Arrays.sort(Group1);

数组变为0 0 0 0 43

第二次迭代。

生成第二个数字后

n= rand.nextInt(55)+1; //lets assume the generated value is 22

的数组变为0 22 0 0 43

调用排序后,

Arrays.sort(Group1);

数组变为0 0 0 22 43

第三次迭代

生成第三个数字之后

n= rand.nextInt(55)+1; //lets assume the generated value is 31

数组变为0 0 31 22 43

调用排序后,

Arrays.sort(Group1);

数组变为0 0 22 31 43

第4次和第5次迭代不会更改数组中的前两个值。 这样,前2个数字将停留为0,这说明了您的结果。

您不能在未排序的数组上使用Arrays.binarySearch 在这种情况下,此操作的结果是不可预测的。

排序将所有零移动到数组的开头。 但是您没有重写它们(因为j正在递增)。

我认为问题在于每次对int数组进行排序。 int数组初始化为0。通过在每次更改插入新随机数的位置时对数组进行排序。 因此,有时您不小心覆盖了随机生成的数字之一,而不是0。

也许不是使用BinarySearch,而是要求使用刚刚使用的排序包含并摆脱排序,直到生成所有随机数。 我不知道确切的语法,因为我已经3年没有用Java编写代码了,但是您可以执行Arrays.asList(Group1).contains(n)之类的操作。 所以...

for (int j = 0; j < 5; j++) {
    //Here, I try to make sure that the range for n is 1-56

    n= rand.nextInt(55)+1;

    while (Arrays.asList(Group1).contains(n)) {
        n = rand.nextInt(55)+1;
    }

    Group1[j] = n;
}

Arrays.sort(Group1);

你好,据我所知,有零位数字的情况,一般是默认分配器是零分配器,那是你没有初始化这个变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM