我现在有一些例外,我一直在努力解决它们,所以任何关于如何修复它们的指南或建议都会很好,而不必依赖别人来帮助他们。 目前我有一个关于如何解决这个问题的建议,但是如果从长远来看如何找出问题的原因将会更好。跟踪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