简体   繁体   中英

Getting null pointer, don't know why

I'm working on a program that displays 8 pairs of cards face down in a 4 x 4 grid, and you need to find the pairs to win.

I've written the classes, and when I try to run, I'm getting a NullPointerException. But I don't know why.

This is the code where the error sits:

public Game(String s)
{
    super(s);
    JPanel cp = (JPanel)getContentPane();
    cp.add("North", scoreLabel);
    surface = new JPanel();
    surface.setLayout(new GridLayout(4, 4));
    cp.add("Center", surface);
    prepareCards();
    for (int x = 0; x < 16; x++)
    {
        Card temp = p.dealCard();
        System.out.println(temp);
        temp.addMouseListener(cardHandle);
        **surface.add(temp);**
    }
}
public static void main(String args[])
{
    *Game game = new Game("TEST GAME PLEASE IGNORE");*
    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.setSize(600, 400);
    game.setVisible(true);
}

Error below (it isn't very helpful).

Exception in thread "main" java.lang.NullPointerException
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    at certClasses.Game.<init>(Game.java:39)
    at certClasses.Game.main(Game.java:44)

Line 39 is in double asterisks (** **), line 44 is in single asterisks (* *).

I've googled the errors, and didn't get anything helpful (stackoverflow quests closed as being unlikely to help others, mostly). I'll post the whole code on pastebin when I can; I'm not at home right now and pastebin is blocked as "Personal Network Storage and Backup".

A null pointer exception is telling you that one of your variables is null, and you are using it in an inappropriate way

This mostly occurs when you try to use a method of an object (Eg):

// gives NPE if temp == null, because null does not have any methods
temp.addMouseListener(cardHandle);

It also occurs when adding null to some collections, Eg Queue (although some collections allow it ):

// gives NPE if temp == null (also if surface == null) 
surface.add(temp);

To debug this in the console you can print the values that are suspect before the null exception occurs:

// you actually have this in your code, so you should see 'null' printed
Card temp = p.dealCard();
System.out.println(temp);
// you should also print this out since surface could possibly be the null nulprit
System.out.println(surface);

I found the problem myself. It was an off-by-one error. I was trying to fill a 4 by 4 grid using only 14 cards, so when it went to find the 15th it got a null. It now runs! Mostly. Anyway, thanks for the help, you pointed me in the right direction.

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