Zariadres Zariadres - 3 months ago 10
Java Question

Add a set amount of random Numbers in an array list while removing duplicates

I can't seem to figure out why it lets duplicates pass. I thought my code implies that I do not want it to have any duplicates. The way I have my code now will add 7 random numbers to my ArrayList which is fine but it also adds duplicate which is not.

import java.util.ArrayList;
import java.util.Random;

public class LotteryNumbers {
private ArrayList<Integer> numbers;


public LotteryNumbers() {

this.drawNumbers();
}

public ArrayList<Integer> numbers() {

Random randomizer = new Random();


int i = 1;
while (i <= 7) {

if (!numbers.contains(randomizer.nextInt(39 + 1))); {

numbers.add(randomizer.nextInt(39) + 1);
i++;

}

}
return this.numbers;
}

public void drawNumbers() {

this.numbers = new ArrayList<Integer>();

}


}

Answer

Fix your numbers() method as follow

public ArrayList<Integer> numbers() {

    Random randomizer = new Random(); 

    int i = 1;
    int num;

    while (i <= 7) {

        num = randomizer.nextInt(39 + 1);

        if (!numbers.contains(num)); {
            numbers.add(num); 
            i++; 
        }

    }

    return this.numbers;
}
Comments