lundi 14 novembre 2016

how to add random Integers to ArrayList without duplication

I have this empty Array List. I wanted to add 6 randomly generated integers (1 to 6) but I don't want it to be duplicated. Somehow I cannot manage to create loop for that. I keep getting duplicated values, and even the size of Array List keep changing. here is my code. Thanks in advance.

    ArrayList al = new ArrayList();

    int rnd = new Random().nextInt(6)+1;

    while(!(al.contains(rnd))){

                for(int i=0; i<=5; i++){

                    al.add(rnd);
                    rnd = new Random().nextInt(6)+1;

                }

                rnd = new Random().nextInt(6)+1;

    }

    System.out.print(al);




Aucun commentaire:

Enregistrer un commentaire