IndexOutOfBounds Exception for Card Shuffler

64 views Asked by At

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!

2

There are 2 answers

0
Mureinik On BEST ANSWER

newDeck starts out as an empty list - calling set on any index in it will produce an IndexOutOfBoundsException as there is no such index.

The good news is that you don't need all this code - you could just use `Collections.shuffle:

public static List<Card> shuffle(List<Card> currDeck) {
    List<Card> newDeck = new ArrayList<>(currDeck);
    Collections.shuffle(newDeck);
    return newDeck;
}
0
Mustafa CEVIK On

You can use debug or try-catch in such error cases.

This is how you need to edit your index value assignment:

int index = rand.nextInt(length);

And you should add the cards to the new list as follows:

 newDeck.add(currDeck.get(index));

Except those...

You can only use java.util.Collections.shuffle() collections class method -> Example

Good luck :)