我現在有一些例外,我一直在努力解決它們,所以任何關於如何修復它們的指南或建議都會很好,而不必依賴別人來幫助他們。 目前我有一個關於如何解決這個問題的建議,但是如果從長遠來看如何找出問題的原因將會更好。跟蹤NullPointerExceptions的最佳方式是什麼?
class Egg extends Bee{
protected void anotherDay() {
eat();
if(age>=3)
{
HashMap<String, Hive> thisHive = Garden.GARDEN.getHiveMap();
Larvae larvae = new Larvae(this.health, this.age);
thisHive.get("a").bees.set(thisHive.get("a").beeIndex, larvae); //-------LINE 27
//thisHive.get("a").replaceBee(larvae) Line 27 was origionally this throwing the same exception
}
age++;
System.out.println("Egg" + " age " + this.age + " health " + this.health);
}
}
import java.util.ArrayList;
class Hive {
protected int honey;
protected int royalJelly;
protected int pollen;
public int beeIndex; // used to know what the index of bee you are in is
public boolean holdAdd;
ArrayList<Bee> bees = new ArrayList<Bee>();
protected Hive(int honeyStart, int royalJellyStart, int pollenStart)
{
bees = new ArrayList<Bee>();
this.setHoney(honeyStart);
this.setRoyalJelly(royalJellyStart);
this.setPollen(pollenStart);
System.out.println("hive made");
System.out.println(honey + " honey");
System.out.println(royalJelly + " royalJelly");
System.out.println(pollen + " pollen");
holdAdd = false;
}
//code removed ...
public void replaceBee(Bee addBee) {
bees.set(beeIndex, addBee);
}
// code removed
protected void anotherDay() {
int i = 0;
for(int k = 0; k < bees.size(); k++)
{
i++;
Bee bee = bees.get(k);
bee.anotherDay(); // ----------------LINE 144
beeIndex = i;
}
// code removed
}
}
public class Garden {
static HashMap<String, Hive> HiveMap = new HashMap<String, Hive>();
public static final Garden GARDEN = new Garden();
public static void main(String[] args) {
GARDEN.anotherDay(); //------------------LINE 21
}
}
//CODE REMOVED
public HashMap<String, Hive> getHiveMap()
{
return Garden.HiveMap;
}
// CODE REMOVED
protected void anotherDay() {
//CODE REMOVED
//should find all Hives and call anotherday() on them each
for(Hive currentHive : HiveMap.values()){
currentHive.anotherDay(); //------------LINE 56
}
}
//CODE REMOVED
}
堆棧跟蹤給你當空指針發生線路。如果只能從特定行中的一個地方拋出空指針,那麼您知道哪個變量爲空並導致了異常。如果該行有多種可能性,調試器將有所幫助。然後,只需回溯調用堆棧即可找到null出現的位置。 – Tobb
那麼,如果您試圖引用一個空對象,並且該對象可以爲空,請在訪問之前檢查它是否爲空。如果對象不能爲null,那麼你的代碼中有一個邏輯錯誤條件,並且需要弄清楚爲什麼。 – OldProgrammer
你的代碼似乎與你的問題無關。他們之間有什麼聯繫?你要求我們爲你調試嗎? – Raedwald