没有正确填充数组Java

时间:2012-05-12 20:06:09

标签: java arrays

运行下一个代码时出现错误“线程异常”主“java.lang.NullPointerException

我认为这与甲板的填充[i2]有关 我尝试做的是每次运行for循环时添加一个值。

有人可以告诉我出了什么问题吗?

public class Deck {
    private Cards cards;
    private String[] suits;
    private String[] ranks;
    private String[] deck;
    private int i2;


    public void Deck() {
        //Instantiate class Cards
        cards = new Cards();
        //run method to get cards / suits
        suits = cards.getSuits();
        ranks = cards.getRanks();

        //Build an array (deck) and fill it with all possible cards
        i2 = 1;
        for (int i = 0; i < suits.length; i++) {

            //Run through ranks
            for (int i1 = 0; i1 < ranks.length; i1++) {
                deck[i2] = suits[i] + ranks[i1];
                2++;
            }
       }
    }
}

3 个答案:

答案 0 :(得分:1)

deck字段尚未初始化,因此访问它会引发NullPointerException。在构建之前,请初始化deck

deck = new String[sizeOfDeck];

sizeOfDeck是表示套牌大小的int

答案 1 :(得分:1)

您是否初始化了deck数组?在外部for循环之前某处必须有这样的声明:

deck = new String[ranks.length * suits.length];

另外,请务必以类似的方式初始化suits类中的ranksCards数组。

答案 2 :(得分:1)

你从未初次化'套牌'。应该是这样的:

deck = new String[ranks.length * suits.length];