IndexOutOfBounds异常(针对卡牌洗牌器)

huangapple go评论85阅读模式
英文:

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);
        newDeck.add(counter, currDeck.get(index));
        currDeck.remove(index);
        length--;
        counter++;
    }

    return newDeck;
}

谢谢!

英文:

I am trying to create a card shuffler method and I am currently having trouble with an IndexOutOfBounds exception. I can't seem to understand why it is erroring out even after working through the code.

public static ArrayList&lt;Card&gt; shuffle(ArrayList&lt;Card&gt; currDeck) {
        var newDeck = new ArrayList&lt;Card&gt;();
        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;
    }

Thanks!

答案1

得分: 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;
}
英文:

newDeck starts out as an empty list - calling set on any index in it will produce an IndexOutOfBoundsException as there is no such index.

The good news is that you don't need all this code - you could just use `Collections.shuffle:

public static List&lt;Card&gt; shuffle(List&lt;Card&gt; currDeck) {
    List&lt;Card&gt; newDeck = new ArrayList&lt;&gt;(currDeck);
    Collections.shuffle(newDeck);
    return newDeck;
}

答案2

得分: 0

以下是翻译好的内容:

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

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

int index = rand.nextInt(length);

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

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

除了那些...

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

祝您好运 IndexOutOfBounds异常(针对卡牌洗牌器)

英文:

You can use debug or try-catch in such error cases.

This is how you need to edit your index value assignment:

int index = rand.nextInt(length);

And you should add the cards to the new list as follows:

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

Except those...

You can only use java.util.Collections.shuffle() collections class method -> Example

Good luck IndexOutOfBounds异常(针对卡牌洗牌器)

huangapple
  • 本文由 发表于 2020年9月27日 04:07:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64082054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定