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

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

IndexOutOfBounds Exception for Card Shuffler

问题

我正在尝试创建一个卡牌洗牌方法,目前遇到了IndexOutOfBounds异常的问题。即使我已经仔细查看了代码,我似乎也无法理解为什么它会在代码运行时出错。

  1. public static ArrayList<Card> shuffle(ArrayList<Card> currDeck) {
  2. var newDeck = new ArrayList<Card>();
  3. int length = currDeck.size();
  4. Random rand = new Random();
  5. int counter = 0;
  6. while (length != 0) {
  7. int index = rand.nextInt(length);
  8. newDeck.add(counter, currDeck.get(index));
  9. currDeck.remove(index);
  10. length--;
  11. counter++;
  12. }
  13. return newDeck;
  14. }

谢谢!

英文:

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.

  1. public static ArrayList&lt;Card&gt; shuffle(ArrayList&lt;Card&gt; currDeck) {
  2. var newDeck = new ArrayList&lt;Card&gt;();
  3. int length = currDeck.size();
  4. Random rand = new Random();
  5. int counter = 0;
  6. while (length != 0) {
  7. int index = rand.nextInt(length - 1);
  8. newDeck.set(counter, currDeck.get(index));
  9. currDeck.remove(currDeck.get(index));
  10. length --;
  11. counter ++;
  12. }
  13. return newDeck;
  14. }

Thanks!

答案1

得分: 0

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

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

  1. public static List<Card> shuffle(List<Card> currDeck) {
  2. List<Card> newDeck = new ArrayList<>(currDeck);
  3. Collections.shuffle(newDeck);
  4. return newDeck;
  5. }
英文:

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:

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

答案2

得分: 0

以下是翻译好的内容:

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

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

  1. int index = rand.nextInt(length);

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

  1. 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:

  1. int index = rand.nextInt(length);

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

  1. 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:

确定