mardi 8 août 2023

Why does sorting my array always make the first two index values a zero?

What I am trying to get is a random number generator that will produce five lines of 5 random numbers 1 through 70 and one more number 1 through 25 like a mega millions ticket.

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class MegaMillions {
    
    public void play() {
        Random rand = new Random();
        int[] numbers = new int[5];
        for(int i = 0; i < 5; i++) {
            numbers[i] = rand.nextInt(69) + 1;
            Collections.shuffle(Arrays.asList(numbers));
            Arrays.sort(numbers);
            System.out.print(numbers[i] + " ");
        }
        Collections.shuffle(Arrays.asList(numbers));
        int megaBall = rand.nextInt(24) + 1;
        System.out.println("(" + megaBall + ")");
    }

}

Here is an example of what I'm getting:

0 0 21 21 35 (1)

0 0 16 26 32 (9)

0 0 39 39 53 (3)

0 0 22 37 51 (14)

0 0 18 18 60 (14)

My understanding was that Collections.shuffle should take care of any repeating integers and Arrays.sort should put in numerical order.




Aucun commentaire:

Enregistrer un commentaire