0

I am trying to build a simple card game as a personal exercise. I have a collection Cards that should contain my deck. To initialize it, I want to pass it a map of what the deck should look like - an integer array (1 to n, 1 to 2) with (n, 1) containing a card type which is resolved within the card class, and (n, 2) containing the number of cards that type I want in the deck. I'm having difficulties with a NullPointer exception, however. Here is my Cards class:

import java.util.LinkedList;

public class Cards{
    private LinkedList<Card> CardDeck;

  ...

    public boolean MakeDeck(int[][] DeckMap){
        /*feed the function a 2D int array (0 to n, 0 to 1)

        @Param - DeckMap[][] - [n][0] to contain card type
        [n][1] to contain DupeCount*/

        //search the array for duplicates
        for (int i = 0; i < DeckMap.length; i++){
            int hold = DeckMap[i][0];
            DeckMap[i][0] = -10;
            for (int j = 0; j< DeckMap.length; j++){        
                if (DeckMap[j][0] == hold){
                    DeckMap[i][0] = hold;
                    return false;
                }       
            }
            DeckMap[i][0] = hold;
        }

        //Add the cards
        // tried variations on this: CardDeck = new LinkedList<Card>;
        for (int i = 0; i< DeckMap.length; i++){
            Card cC = new Card();
            cC.initializeCard(DeckMap[i][0], DeckMap[i][1]);
            CardDeck.addLast(cC);
        }
        return true;


    }
}

The NullPointer error occurs at the cC.addLast line - since I have initialized the Card class, the Null Pointer should refer to the CardDeck LinkedList I want to add the Card to, I think. But I can't work out how to initialize the list. Or is the .initializeCard call the problem (code below)? Thanks in advance for your help and apologies if I've missed something obvious.

Error:

java.lang.NullPointerException at towergame.Cards.MakeDeck(Cards.java:75)

  public class Card {

        private static String cName;
        private static int cDuplicateCount;
        public static cEffect myEffects;

        public final void initializeCard(int inEffect, int DupeCount){
            myEffects = new cEffect();
            myEffects.setEffect(inEffect);
            cName = myEffects.getCardType();
            cDuplicateCount = DupeCount;
        }
     ...
   }

1 Answer 1

2

Instead of this private LinkedList<Card> CardDeck;

use this private LinkedList<Card> CardDeck = new LinkedList<Card>();

it is throwing NPE because cardDeckhas not been initialized.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.