vendredi 4 novembre 2022

java.lang.StackOverflowError on a recursive function

I want to draw a random card from a deck and validates that it's always unique. I'm using the cardGenerator() recursive function to do that. If the random card picked has been shown then it calls itself again. Need a work around or if any of yall got a better logic please let me know.

import java.util.ArrayList;
import java.util.Random;

public class App {
    static ArrayList<Integer[]> deck = new ArrayList<>();
    static ArrayList<Integer[]> dealer = new ArrayList<>();

    static Integer[] cardGenerator() throws Exception{
        Random random = new Random();
        Integer[] card = {0, 0};
        Integer num = random.nextInt(13);
        Integer shape = random.nextInt(4);
        Integer[] deckSet = deck.get(num);
        if(deckSet[shape] == 1){
            deckSet[shape] = 0;
            deck.set(num, deckSet);
            card[0] = num;
            card[1] = shape;
            return card;
        }
        else return cardGenerator();
    }

    public static void main(String[] args) throws Exception {
        for(int i = 0; i < 13; i++){
            deck.add(deckSet);
        }
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
        dealer.add(cardGenerator());
    }
}

expecting for dealer to store 5 unique cards, but java.lang.StackOverflowError occured on the cardGenerator function.




Aucun commentaire:

Enregistrer un commentaire