Java, random numbers (without repetition)

3

I have a question about generating numbers without repeating.

I can already generate random numbers from 1 to 8 which is my goal. The odd thing is that it generates repeated numbers (duplicates, triplicates or even more). In my program there can be no number repeated. My code so far:

for (int k = 1; k < (gameBtn.length / 2) + 1; k++)    // 1 até 8
        {
            int z= 8 + (int)(Math.random() * (1 - 8));   // Máximo 8, mínimo 1
            gameList.add(z);    // Imprime os números de 1 a 8, podendo sair repetidos
        } 

In other words, I want to make a if (numeros_anteriores_que_sairam != novo numero) . If it confirms, it prints gameList.add(z) , otherwise it does not print the number that came out, (or it eliminates equal numbers) or it does something else without printing the number. All numbers must be different!

    
asked by anonymous 17.04.2015 / 12:35

2 answers

4

Try this:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Aleatorio8 {
    public static void main(String[] args) {
        List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
        Collections.shuffle(lista);
        System.out.println(lista);
    }
}

In your code I think it would look like this:

gameList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
Collections.shuffle(gameList);

Or maybe so:

List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
Collections.shuffle(lista);
gameList.addAll(lista);
    
17.04.2015 / 12:40
0

This is a standard method to generate random numbers in Java:

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {


    Random rand = new Random();

    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

See the relevant JavaDoc . In practice, the class java.util.Random is most often replaced by java.lang.Math.random () .

    
24.08.2015 / 22:12