【发布时间】:2015-12-21 01:56:30
【问题描述】:
当我运行我的代码时,我不断收到IndexOutOfBoundsException。我使用的是ArrayList,所以我不确定为什么会这样。
我的ArrayList 是
ArrayList<Card> cards = new ArrayList<Card>();
这是发生错误的地方
public static void printCard(){
System.out.printf("%-20s %-20s\n", player1.name, player2.name);
for(int i = 0; i < 24; i++){
System.out.printf("%-20s %-20s\n", player1.getCard(i), player2.getCard(i));
} System.out.println();
}
播放器类
public class Player {
public Deck mainDeck;
public Deck sideDeck;
public String name;
public int duelsWon;
public int totalCompares;
public Player(String name){
this.name=name;
mainDeck = new Deck();
sideDeck = new Deck();
duelsWon = 0;
totalCompares = 0;
}
public void addCard(Card newCard){
sideDeck.addCard(newCard);
}
public Card drawCard() throws OutOfCardsException{
if(mainDeck.numCards() == 0) {
addSideDeck();
}
if(mainDeck.numCards() == 0){
throw new OutOfCardsException();
}
Card c = mainDeck.drawCard();
return c;
}
public Card getCard(int i){
return mainDeck.cards.get(i);
}
/*public Card getCard(int i){
if(i < mainDeck.cards.size()) {
return mainDeck.cards.get(i);
}else{
}
return null;
}*/
public void addSideDeck(){
sideDeck.shuffle();
System.out.println("sideDeck: " + sideDeck.numCards());
for(int i = 0; i < sideDeck.numCards(); i++){
Card c = sideDeck.drawCard();
mainDeck.addCard(c);
}
}
}
甲板类
import java.util.ArrayList;
import java.util.Random;
public class Deck {
ArrayList<Card> cards = new ArrayList<Card>();
public Deck() {
}
public void addCard(Card c){
cards.add(c);
}
public Card drawCard(){
Card c = cards.remove(cards.size() - 1);
return c;
}
public Card getCard(){
return cards.get(cards.size() - 1);
}
public int numCards(){
return cards.size();
}
public void shuffle()
{
int index;
Card temp;
Random random = new Random();
for (int i = cards.size() - 1; i > 0; i--)
{
index = random.nextInt(i + 1);
temp = cards.get(index);
cards.set(index, cards.get(i));
cards.set(i, temp);
}
}
}
【问题讨论】:
-
这段代码不足以说明问题。
-
请添加完整的堆栈跟踪
-
很抱歉。我刚刚添加了我的播放器和套牌类。
-
异常告诉你出了什么问题 - 你正在访问一个只有 6 个元素的
ArrayList中的索引 6(即索引 0、1、2、3、4、5) -
很遗憾,我仍然认为您没有提供足够的信息。当 i 大于或等于 Deck 类的卡片 ArrayList 中的 cards.size() 时,您会得到 ArrayOutOfBoundsException,但是您还没有展示如何将卡片添加到卡片组类。如果每个玩家的 mainDeck 没有至少 24 张卡,那么您将始终看到此错误。
标签: java indexoutofboundsexception