I’m having a little trouble with some code I’m writing. Basically, I’m trying to “shuffle” a stack collection like a deck of cards, but for some reason, one of the temporary stacks I’m using won’t empty completely, and this causes an empty collection exception on the next run around. I traced the code and the output by hand, and the elements are being left in temporary stack 1 (the code is below). I’m really not sure why this is happening! If you have any insight on this, it’d be really helpful.
Here is a link to the problem method: http://pastebin.com/cxJCmemZ
public void shuffleCards(LinkedStack<UnoCard> deck) {
int tempIndex;
LinkedStack<UnoCard> tempCardStack1 = new LinkedStack<UnoCard>();
LinkedStack<UnoCard> tempCardStack2 = new LinkedStack<UnoCard>();
//Fisher-Yates shuffle
for (int i = (deck.size() - 1); i >= 0; i--) {
tempIndex = ((int)(i * Math.random()));
System.out.println("i is: " + i);
System.out.println("tempIndex is: " + tempIndex);
//swap if cards are different
if (tempIndex != i) {
//pop face down cards up to first card onto temporary stack
System.out.println("Popping up to first card");
for(int j = 0; j <= tempIndex; j++) {
UnoCard tempCard = faceDownCards.pop();
System.out.println(tempCard.toString());
tempCardStack1.push(tempCard);
}
//pop face down cards up to second card onto temporary stack
System.out.println("Popping up to second card");
for(int j = (tempIndex + 1); j <= i; j++) {
UnoCard tempCard = faceDownCards.pop();
System.out.println(tempCard.toString());
tempCardStack2.push(tempCard);
}
//replace first card in second card position
System.out.println("Replacing first card");
UnoCard tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
//place second card in temporary stack
System.out.println("Transferring second card");
tempCard = tempCardStack2.pop();
System.out.println(tempCard.toString());
tempCardStack1.push(tempCard);
//replace temporary stack
System.out.println("Replacing second stack");
for(int j = 0; j < tempCardStack2.size(); j++) {
tempCard = tempCardStack2.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
}
//replace second card in first card position
System.out.println("Replacing second card");
tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
//replace temporary stack
System.out.println("Replacing first stack");
for(int j = 0; j < tempCardStack1.size(); j++) {
tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
}
}
}
}
if you pop a stack the size shrinks so the for loop will only run for size/2 times
so the ending loops should really be