创建ArrayList时出现OutOfBoundsException错误

时间:2016-02-24 22:47:22

标签: java arraylist indexoutofboundsexception

我正在尝试制作一副纸牌。到目前为止,我有这个:

import java.util.*;
public class Card {
    public static void main(String[] args) {
        ArrayList<String> rank = new ArrayList<String>(Arrays.asList("Ace", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"));
        ArrayList<String> suite = new ArrayList<String>(Arrays.asList("Spades", "Hearts", "Clubs", "Diamonds"));
        ArrayList<String> deck = new ArrayList<String>();
        String card;


        for (int i = 0; i < rank.size(); i++) {
            for (int p = 0; i < suite.size(); p++) {
                card = rank.get(i) + " of " + suite.get(p);
                deck.add(card);
            }
        }
        System.out.println(deck);
    }
}

我在这一行收到IndexOutOfBoundsException错误:

card = rank.get(i) + " of " + suite.get(p);

2 个答案:

答案 0 :(得分:2)

第二个循环中有错误:

for (int p = 0; i < suite.size(); p++) {

应该是

for (int p = 0; p < suite.size(); p++) {

答案 1 :(得分:0)

我相信它是因为您在内部for循环中使用i < suite.size();