How to randomize the values of an object in java

2

I am building a card game program, where at a certain point he should mix the cards and pick up the one in position 0, but I can not do that. Here is the code:

public class Baralho {
Carta[] cartas = new Carta[52];
String[] naipes = {"Copas", "Espada", "Ouros", "Paus"};
String[] nomes = {"As", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
String coringa;
Random aleatorio = new Random();
public Baralho() {
    int cont = 0;
    for (String naipe : naipes) {
        for (String nome : nomes) {
            Carta cartas = new Carta();
            cartas.setNaipe(naipes);
            cartas.setNome(nomes);
            this.cartas[cont] = cartas;
            this.embaralha(naipes);
            cont++;
        }
    }
    System.out.println(cartas);//Teste
}
public void embaralha(String[] carta) {//Esta parte aqui!
    aleatorio.naipes();
}
public void daCarta() {
    for (int i = 0; i < cartas.length; i++) {
        if (cartas[0] == null) {
            break;
        }else {
            System.out.println(cartas[0]);
        }
    }
}
public boolean temCarta() {
    boolean TouF = true;
    for (int i = 0; i < cartas.length; i++) {
        if (cartas[i] != null) {
            TouF = false;
        }else {
            TouF = true;
        }
    }
    return TouF;
}
public void imprime() {
    for (int i = 0; i < cartas.length; i++) {
        System.out.println(cartas[i]);
    }
}

}

    
asked by anonymous 01.05.2018 / 22:52

1 answer

2

You can use the shuffle () of the Collections class. It receives a list as parameter. Since you have an array, use Arrays.asList() to convert the array to list.

Assuming you have an array called pack , all you need to shuffle it is to use:

Collections.shuffle(Arrays.asList(baralho));

The following example will print a random value each time the program runs:

public static void main(String[] args) {

    String[] baralho = new String[20];
    for (int i = 0; i < baralho.length; i++) {
        baralho[i] = String.valueOf(i);
    }

    Collections.shuffle(Arrays.asList(baralho));
    System.out.println(baralho[0]);
}

If this answer helped, mark it as correct. ;)

Source: Random shuffling

    
02.05.2018 / 14:30