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!
newDeck
starts out as an empty list - callingset
on any index in it will produce anIndexOutOfBoundsException
as there is no such index.The good news is that you don't need all this code - you could just use `Collections.shuffle: