1

我正在尝试创建一个洗牌器方法,但我目前遇到了 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;
    }

谢谢!

4

2 回答 2

0

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

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

public static List<Card> shuffle(List<Card> currDeck) {
    List<Card> newDeck = new ArrayList<>(currDeck);
    Collections.shuffle(newDeck);
    return newDeck;
}
于 2020-09-26T20:17:42.930 回答
0

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

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

int index = rand.nextInt(length);

您应该将卡片添加到新列表中,如下所示:

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

除了那些...

您只能使用java.util.Collections.shuffle()集合类方法 ->示例

祝你好运 :)

于 2020-09-26T20:40:15.110 回答