当我运行我的代码时,我总是收到IndexOutOfBoundsException
。我正在使用ArrayList
,所以我不确定为什么会发生这种情况。 我ArrayList
是Arraylist IndexOutOfBoundsException?需要一些帮助
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();
}
Player类
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);
}
}
}
这段代码不足以说明。 – Satya
请加完整stacktrace –
对不起。我只是添加了我的球员和甲板课程。 – Aero