Search code examples
javaarraysintuniqueinfinite-loop

Java trying to fill int array with unique numbers


I'm new on this site and i've got very poor english, forgive me for this.

I have a problem with my function:

public void generate(int[] array) {
    int i=0;
    boolean isvalid=true;
    while (i < 5) {
        int rng = (int)(Math.random()%100*100);
        for (int j=0; j < 5; j++) {
            if (array[j] == rng) {
                isvalid=false;
                System.out.println("duplicate: "+rng);
            }
        }
        if (isvalid) {
            array[i]=rng;
            System.out.println(rng);
            i++;
        }
    }
}

I need to fill up a 5 size int array with unique random numbers between 0 and 100. This is work, but sometimes bugging, and starting an endless loop, and for some reason my compiler (netbeans) cant generate a new random number, just loop some. For ex:

duplicate 62
duplicate 62
duplicate 64
duplicate 97
duplicate 97
duplicate 64
duplicate 97
duplicate 62
duplicate 64
duplicate 62
duplicate 64
duplicate 62
duplicate 97
duplicate 97
duplicate 56
duplicate 97
duplicate 62
duplicate 56
duplicate 56
duplicate 56
duplicate 64
duplicate 56
duplicate 62
duplicate 56

Someone have any usefull tips for my problem? Thanks in advance!


Solution

  • Once isvalid = false; it is never true again and therefore you get an infinite loop because you don't increment i in that case (quick-fix should be to isvalid = true inside the while).