简体   繁体   中英

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>();

    }


}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM