gpt4 book ai didi

java - 代码运行一段时间后出现 IndexOutOfBoundsException

转载 作者:行者123 更新时间:2023-12-02 04:52:52 25 4
gpt4 key购买 nike

我有 10 张卡片的数组。在“回合”的过程中,我向数组添加一张卡片,然后从数组中删除一张卡片(并不总是相同的)。该代码在前 6-7 回合中效果很好,然后抛出 IndexOutofBoundsException尝试从数组中获取特定卡时出错。它是 getCard 中的东西,但为什么它以前可以正常工作,特别是当我或多或少在数组中保留相同数量的对象时?

打印输出:1. J♥ 2. 10♣ 3. 10◆ 4. 9♠ 5. 9◆ 6. 7♥ 7. 7♣ 8. 6♣ 9. 5♣ 10. 2◆ 11. 2♥

玩家丢弃卡 = 11

(显示时我向索引添加 +1。)

ArrayList<Card> handCard = new ArrayList<Card>(10);

//Beginning of turn
playerHand.addCard(newCard);

//End of turn
int playerDiscardChoice = scanner.nextInt();
Card playerDiscardCard = playerHand.getCard(playerDiscardChoice-1);
playerHand.removeCard(playerDiscardCard);

//Methods

//where I initialize the playerHand
public ArrayList buildHand(Deck deck){

for (int i = 0; i < 10; i++)
{
Card newCard = deck.drawFromDeck();
handCard.add(newCard);
}
return handCard;
}
public ArrayList addCard (Card newCard){
handCard.add(newCard);
Collections.sort(handCard);
return handCard;
}

public Card getCard (int index){
Card returnCard = handCard.get(index);
return returnCard;
}

public ArrayList removeCard (Card newCard){
handCard.remove(newCard);
//Collections.sort(handCard);
return handCard;
}

//Exception error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10,
Size: 10
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at Marty.company.Hand.getCard(Hand.java:18)
at Marty.company.Main.runHumanTurn(Main.java:103)
at Marty.company.Main.newGame(Main.java:41)
at Marty.company.Main.main(Main.java:15)

最佳答案

IndexOutOfBoundsException给出的信息中,上面写着Index: 10, Size: 10 。您一定打过getCard(10)尺寸为 10 或以下的列表中。

大小为 10 的列表的索引范围为 0 到 9,因此列表中没有索引 10。

当您调用new ArrayList<Card>(10)时,您仅设置其容量而不是其大小。它的大小是它包含的元素数量,而它的容量是它当前可以容纳的元素数量。

因此,当您调用new ArrayList<Card>(10)时添加一张卡片,它仍然只是一个容量为 10、大小为 1 的 ArrayList。看起来初始化 ArrayList 后可能需要添加 10 张卡片。

关于java - 代码运行一段时间后出现 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29056512/

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