samedi 26 septembre 2020

IndexOutOfBounds Exception for Card Shuffler

I am trying to create a card shuffler method and I am currently having trouble with an IndexOutOfBounds exception. I can't seem to understand why it is erroring out even after working through the code.

public static ArrayList<Card> shuffle(ArrayList<Card> currDeck) {
        var newDeck = new ArrayList<Card>();
        int length = currDeck.size();
        Random rand = new Random();
        int counter = 0;

        while (length != 0) {
            int index = rand.nextInt(length - 1);
            newDeck.set(counter, currDeck.get(index));
            currDeck.remove(currDeck.get(index));
            length --;
            counter ++;
        }


        return newDeck;
    }

Thanks!




Aucun commentaire:

Enregistrer un commentaire