[英]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 - 1);
newDeck.set(counter, currDeck.get(index));
currDeck.remove(currDeck.get(index));
length --;
counter ++;
}
return newDeck;
}
谢谢!
newDeck
开始是一个空列表——在其中的任何索引上调用set
都会产生一个IndexOutOfBoundsException
因为没有这样的索引。
好消息是你不需要所有这些代码 - 你可以只使用`Collections.shuffle :
public static List<Card> shuffle(List<Card> currDeck) {
List<Card> newDeck = new ArrayList<>(currDeck);
Collections.shuffle(newDeck);
return newDeck;
}
在这种错误情况下,您可以使用debug或try-catch 。
这是您需要如何编辑索引值分配:
int index = rand.nextInt(length);
您应该将卡片添加到新列表中,如下所示:
newDeck.add(currDeck.get(index));
除了那些...
您只能使用java.util.Collections.shuffle()
集合类方法 -> 示例
祝你好运 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.