[英]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.