ArrayIndexOutOfBounds错误

时间:2014-12-18 13:39:37

标签: java arraylist indexoutofboundsexception

我有一个问题。

public class Deck {
    //deck contents returns every card in the deck

    String[] suits = {"Clubs", "Hearts", "Diamonds", "Spades"};
    String[] ranks = {"Deuce", "Three", "Four", "Five", "Six", "Seven",
                      "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"};
    int[] values = {2,3,4,5,6,7,8,9,10,10,10,10,11};

    ArrayList<Card> deck = new ArrayList<Card>();

    ArrayList<Card> cardsDealt = new ArrayList<Card>(); //unused here

            Random rand = new Random(); //unused here

    public Deck(){
            for(int i = 0; i < suits.length; i++){
                for(int k = 0; i < ranks.length; k++){
                        deck.add(new Card(suits[i], ranks[k], values[k]));          
                } 
            }
        }

我收到IndexOutOfBoundsException错误。我的任务是创建一个Deck对象,然后将52个Card对象添加到名为deck的ArrayList中。我写了for循环来创建卡片组中每张可能的52张牌。错误是什么?

2 个答案:

答案 0 :(得分:4)

你的问题在这里:

for(int i = 0; i < suits.length; i++){
    for(int k = 0; i < ranks.length; k++){
                   ^
        deck.add(new Card(suits[i], ranks[k], values[k]));          
    } 
}

不是i < ranks.length而是k < ranks.length

for(int i = 0; i < suits.length; i++){
    for(int k = 0; k < ranks.length; k++){
        deck.add(new Card(suits[i], ranks[k], values[k]));          
    } 
}

答案 1 :(得分:1)

在此处交换i的{​​{1}}:

k

for(int k = 0; i < ranks.length; k++){

您不断检查for(int k = 0; k < ranks.length; k++){ 是否小于i来终止循环(在此内循环中,它总是......),所以ranks.length继续增加超过k,因此一旦您尝试访问套装[13]就会出现错误。