How to randomize the values of an object in java

Asked

Viewed 199 times

2

I am building a card game program, in which at a certain moment he must mix the cards and pick up the one that is at position 0, but I cannot do that. Follows 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]);
    }
}

}

1 answer

2


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

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

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

The example below 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 that answer helped you, mark it as correct. ;)

Source: Random Shuffling

Browser other questions tagged

You are not signed in. Login or sign up in order to post.