samedi 27 mars 2021

array with random ints but no duplicates and first number showing

This is probably already asked, but I am a little new to Java and it is a little difficult for me to understand. I created a for loop to add random integers into my array, but when the integer is already in the array, restart the loop. But I keep on getting the same integers into the array + when there already is a duplicate, the array size increases. Does anyone know what I'm doing wrong?

Random r = new Random();
        int[] tes = new int[5];
        for (int i = 0; i < tes.length; i++) {
            int q = r.nextInt(10);
            for (int j = 0; j < i; j++) {
                if (q == tes[j]){
                    i=i-1;
                }
            }
            tes[i] = q;
            System.out.println(tes[i]);
        }

and the output:

enter image description here




Aucun commentaire:

Enregistrer un commentaire