我正在写一些我正在写的代码有点麻烦。基本上,我试图像一副牌一样“洗牌”一个堆栈集合,但由于某种原因,我正在使用的一个临时堆栈不会完全清空,这会导致下一次运行时出现空集合异常周围。我手动跟踪代码和输出,并将元素留在临时堆栈1中(代码如下)。我真的不确定为什么会这样!如果您对此有任何见解,那将非常有用。
以下是问题方法的链接: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);
}
}
}
}
答案 0 :(得分:2)
如果你弹出一个堆栈,那么大小会缩小,所以for循环只会运行大小/ 2次
所以结束循环应该是
while(!tempCardStack1.isEmpty()){
tempCard = tempCardStack1.pop();
System.out.println(tempCard.toString());
faceDownCards.push(tempCard);
}