繁体   English   中英

获取空指针,不知道为什么

[英]Getting null pointer, don't know why

我正在开发一个程序,该程序以8 x 4的面朝下显示8对纸牌,您需要找到能赢的纸牌对。

我已经编写了这些类,并且当我尝试运行时,我得到了NullPointerException。 但是我不知道为什么。

这是错误所在的代码:

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

出现以下错误(不是很有帮助)。

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)

第39行是双星号(** **),第44行是单星号(* *)。

我已经搜索了错误,但没有得到任何帮助(关闭stackoverflow任务是因为它不太可能帮助其他人)。 如果可以,我会将整个代码发布到pastebin上; 我现在不在家,pastebin被阻止为“个人网络存储和备份”。

空指针异常告诉您变量之一为空,并且您以不适当的方式使用它

当您尝试使用对象的方法(例如)时,通常会发生这种情况:

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

当向某些集合(例如Eg Queue添加null时,也会发生这种情况(尽管某些集合允许 ):

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

要在控制台中对此进行调试,您可以null异常发生之前打印可疑null

// 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);

我自己发现了问题。 这是一个错误的错误。 我试图只用14张卡片来填充4 x 4网格,所以当它找到第15张卡片时就得到了空值。 现在运行! 大多。 无论如何,感谢您的帮助,您为我指明了正确的方向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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