洗牌器的 IndexOutOfBounds 异常

IndexOutOfBounds Exception for Card Shuffler

我正在尝试创建洗牌器方法,但我目前遇到了 IndexOutOfBounds 异常问题。我似乎无法理解为什么即使在完成代码后它仍会出错。

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;
    }

谢谢!

newDeck 开始时是一个空列表 - 在其中的任何索引上调用 set 都会产生 IndexOutOfBoundsException,因为没有这样的索引。

好消息是您不需要所有这些代码 - 您可以只使用 `Collections.shuffle:

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

在这种错误情况下,您可以使用 debugtry-catch

这是您需要编辑索引值分配的方式:

int index = rand.nextInt(length);

您应该按如下方式将卡片添加到新列表中:

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

除了那些...

您只能使用 java.util.Collections.shuffle() 集合 class 方法 -> Example

祝你好运:)