英文:
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<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;
}
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<Card> shuffle(List<Card> currDeck) {
List<Card> newDeck = new ArrayList<>(currDeck);
Collections.shuffle(newDeck);
return newDeck;
}
答案2
得分: 0
以下是翻译好的内容:
在这种错误情况下,您可以使用debug或try-catch。
以下是您需要编辑索引值分配的方式:
int index = rand.nextInt(length);
并且您应该按以下方式将卡片添加到新列表中:
newDeck.add(currDeck.get(index));
除了那些...
您只能使用java.util.Collections.shuffle()
集合类方法 -> 示例
祝您好运
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论