Java random numbers with no duplicates for a lotte

2019-06-12 06:48发布

问题:

This question already has an answer here:

  • Java Random number with no duplicate [duplicate] 5 answers

For my computer science class we're supposed to redo a lottery code we have already created, but now using methods and arrays. This is what I've done so far, but I can't figure out for the life of me why it is still duplicating the numbers and I can't find anything online that is close enough to what we're supposed to be doing/topics we have gone over. I am very new to this.

    public static void generaterand (int [] r)
    {

    Random  randomgen = new Random();

    boolean done;
    int i = 0;
    int j = 0;

    done = false;

    while (done == false)
    {
        for (i=0; i<6; i++)
        {
            r[i] = randomgen.nextInt(54)+1;

                for (j=0; j<6; j++)
                {   
                    if (r[i] != r[j])
                    {
                        done = true;
                    }
                }
        }
    }
    System.out.printf ("Lottery Numbers: %d %d %d %d %d %d\n", r[0], r[1], r[2], r[3], r[4], r[5]); 
}

回答1:

An efficient method in Java is to use a hashtree datatype, since it cannot store duplicates.