[英]Null Pointer Exception when trying to set a value
幾乎我在制作一系列稱為Spots
的物體,這些物體象征着骰子的不同面。
它需要用戶輸入(在此示例中,手動設置為3),然后創建使Spots
滾動的隨機數從1到6。
但是,當我在有序創建的Spots
數組上使用rollAgain()
方法時,即使我在兩個for循環中使用相同的可變長度(一個創建和一個滾動斑點),我都會得到一個空指針。
我的密碼
全局變量
private Spots[] spots;
private int x = 3;
建設者
public Director(JFrame window, String args[]) {
JMenuBar menus = new JMenuBar();
window.setJMenuBar(menus);
menus.add(makeFileMenu());
window.getContentPane().add(makePanel(), BorderLayout.WEST);
window.getContentPane().add(makeSpots(x), BorderLayout.CENTER);
rollAgain();
}
rollAgain()方法
public void rollAgain() {
int v = 1 + (int) (Math.random() * 6);
for (int i = 0; i < x; i++) {
spots[i].setValue(v);
}
}
makeSpots()方法
private JComponent makeSpots(int x) {
JPanel p = new JPanel();
p.setBorder(BorderFactory.createTitledBorder("Dice"));
Spots[] spots = new Spots[x];
for (int i = 0; i < x; i++) {
spots[i] = new Spots(200, 200);
spots[i].setBorder(BorderFactory.createEtchedBorder());
p.add(spots[i]);
}
return p;
}
您正在設置局部變量
Spots[] spots = new Spots[x];
這不會更改字段(碰巧具有相同的名稱)
private Spots[] spots;
最簡單的解決方案是沒有局部變量
this.spots = new Spots[x];
您需要在構造函數中實例化一個新的Spots數組。
this.spots = new Spots[x];
spots[i].setValue(v);
從這一行來看,我的猜測是數組中的Spot
對象為null。
該錯誤在您的makeSpots()
方法中。 您無需更新字段x
的值,而是使用局部變量。 在方法的開頭添加this.x = x
。
在您的makeSpots()
方法中,您正在創建一個名為spots的新Spots對象:
Spots[] spots = new Spots[x];
這樣可以有效地從方法中隱藏您的私有成員變量點。 相反,請在您的makeSpots()方法中執行以下操作:
spots = new Spots[x];
您要聲明一個全局“ spots”數組,然后在makeSpots()中使用局部變量(也稱為“ spots”)創建這些斑點。 只是替代
Spots[] spots = new Spots[x];
通過
spots = new Spots[x];
因此全局變量會獲得一個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.