samedi 22 octobre 2016

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?

I am trying to create a method that produces lottery numbers with a random number generator. There are two groups of numbers. Group one is supposed to have five different numbers that appear in sorted order, with a range of 1-56. Group two consists of a single number with a range of 1-46. When I run the program, group one always begins two consecutive zeros even though I tried to write the code in a way that doesn't allow group one to have zeros or repeating numbers. At first I thought that the problem must have something to do with the random number generator, so I tried debugging the project in NetBeans. As I stepped through the lines of code, I could see the values assigned to n, which is the variable that holds the numbers produced by the random generator. The values of n were 54, 50, 11, 49, and 28. In the program, the values of n are put into a sorted array. So the output for group one should have been 11, 28, 49, 50, 54, but instead it was 0, 0, 11, 28, 49.

Here is my code:

 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 the output:

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

I've tried using ThreadLocalRandom instead, but I still had the same problem. Does anyone know what I am doing wrong? Any and all advice is much appreciated.




Aucun commentaire:

Enregistrer un commentaire