简体   繁体   中英

Not properly filling array Java

When running next code I get a error " Exception in thread "main" java.lang.NullPointerException "

I think it has to do with the filling of deck[i2] What i try to do is adding a value each time the for loop is run.

Can someone tell me what's going wrong?

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++;
            }
       }
    }
}

The deck field hasn't been initialized, so accessing it throws a NullPointerException . Before building it, initialize deck :

deck = new String[sizeOfDeck];

Where sizeOfDeck is an int representing the size of the deck.

Did you initialize the deck array? there must be a statement like this somewhere before the outer for loop:

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

Also, be sure to initialize the suits and ranks arrays in the Cards class in a similar way.

You never initialized 'deck'. Should be something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM