首页 > 解决方案 > 为什么我的数组建模一副卡片返回空卡片对象?

问题描述

所以这是我的甲板类填充一副纸牌

/**
Constructs a deck with 52 cards
*/
public Deck() {

    int k = 0;  // counter to keep track of elements in the deck array

    // nested for loops to populate the deck of cards with 4 suits and 13 possible rankings
    for (int i = 1; i < SUITS; i++) {
        for (int j = 1; j < RANKS; j++) {
            deckOfCards[k] = new Card(i, j);  // adds the cards to the deck array 
            k++;                              // increment the elements counter by 1
            System.out.println(deckOfCards[k]);
        }
    }

}

这是我的卡片课程,尽管我几乎可以肯定这部分没有任何问题

public class Card {

    private int rank;
    private int suit;

    /**
    * @param suit the suit of the card in a deck 
    * @param rank the rank of the card in a deck 
    */
    public Card(int suit, int rank) {

        this.rank = rank;       // initializing the rank 
        this.suit = suit;       // initializing the suit
    }

当我打印出套牌中的卡片时,我会被null退回。任何想法为什么?

标签: javaarraysnull

解决方案


deckOfCards[k] = new Card(i, j);
k++;
System.out.println(deckOfCards[k]);

您正在设置deckOfCards[k]但正在打印deckOfCards[k+1].


推荐阅读