[英]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.