【问题标题】:IndexOutOfBounds Exception for Card Shuffler洗牌器的 IndexOutOfBounds 异常
【发布时间】:2021-01-12 20:21:23
【问题描述】:

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

谢谢!

【问题讨论】:

  • 那么,哪一行和哪个值触发了错误?您是否检查过counter 的值永远不会大于牌组的大小?
  • 你为什么不用Collections.shuffle(currDeck);
  • 您应该使用newDeck.add 而不是newDeck.set

标签: java arraylist random card


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    int index = rand.nextInt(length);
    

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

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

    除了那些...

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

    祝你好运:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多