我一生都无法弄清楚为什么这种随机播放方法不起作用:
public void deckShuffle(int shuffle) {
Random rand = new Random();
int targetCard, cardValue, cardSuit;
Card temp, card;
for (int x = 0; x < shuffle; x++) {
for(int y = 1; y < 52; y++) {
targetCard = 51 - rand.nextInt(51);
temp = getCard(targetCard);
cardValue = temp.getCardValue();
cardSuit = temp.getCardSuit();
removeCard(targetCard);
addLast(cardValue, cardSuit);
}
}
这是我删除卡并添加最后的代码:
public void removeCard(int index) {
if (head.next == null || index < 1) {return;}
if (count > 0 && index <= count) {
Card current = head;
for (int x = 0; x < index; x++) {
current = current.next;
}
current.next = current.next.next;
count--;
}
}
public void addLast(int cardValue, int cardSuit) {
Card temp = new Card(cardValue, cardSuit, null);
Card current = head; // POINTER
while (current.next != null) {
current = current.next;
}
current.next = temp;
count++;
}
我试图找出为什么代码不起作用。当我运行一种方法来打印一副 52 张牌并洗牌时,所有牌都显示为 2 颗红心。我知道这不是我的构建方法,因为我在编写 shuffle 方法之前对其进行了测试。
我明白了,伙计们。我的移除卡方法无法正常工作,但现在可以正常洗牌了。感谢您的帮助!
最佳答案
为什么不直接使用Collections.shuffle
方法呢?
有关更多信息,也许您应该发布您的 Card 类?那么至少有人可以尝试运行代码(如果他们愿意的话)。
关于java - 如何在java中打乱链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28683908/