gpt4 book ai didi

java - 如何使索引小于大小

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:58 26 4
gpt4 key购买 nike

我无法让索引小于 arrayList 的大小,以便我可以发牌。这是我的代码:

import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import java.util.ArrayList;

public class Deck {
ArrayList<Card> unusedCards = new ArrayList<Card>();
ArrayList<Card> usedCards = new ArrayList<Card>();
Card newCard = new Card();
Random rand = new Random();


//Creates a Deck of 52 randomly ordered card objects (No repeats)
public Deck() {
for (int i = 0; i <= 52; i++) {
while (unusedCards.contains(newCard)) {
newCard = new Card();
}
unusedCards.add(newCard);
}
}
//shuffles the arraylist of the deck of cards, making it so the cards are dealt in a different order
public void shuffle(){
Collections.shuffle(unusedCards);
}

//Boolean is true when the Unsed deck has no cards left
public boolean isEmpty(){
if (unusedCards.size() == 0) return true;
else return false;
}

//returns an arraylist containing the specified number of cards
public ArrayList<Card> Deal(int numToDeal){
ArrayList<Card> DealCards = new ArrayList<Card>();

for (int i = 0; i < numToDeal; i++){
int index = rand.nextInt(50);
DealCards.add(unusedCards.get(index));
usedCards.add(unusedCards.get(index));
unusedCards.remove(unusedCards.get(index));
}

return DealCards;
}

}

当我尝试发多张牌时,我不断收到此错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 48, Size: 48
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at nnajiO.Deck.Deal(Deck.java:41)
at nnajiO.CrazyEights.main(CrazyEights.java:26)

如果您能提供帮助,谢谢。

最佳答案

您将 53 张牌放入牌堆中。

for (int i = 0; i <= 52; i++) {

数组中索引的范围是0 .. length-1 。因此您想使用<上述语句中的运算符而不是 <=运算符。

另一个问题类似。您正在从 unusedCards 中删除卡片使用静态随机范围时:

int index = rand.nextInt(50);

在这种情况下,应该更改为以下内容,以避免选择超出范围的索引:

int index = rand.nextInt(unusedCards.size());

关于java - 如何使索引小于大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27975043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com