【发布时间】:2013-12-10 16:03:47
【问题描述】:
我现在遇到了一些这样的异常,我一直在努力解决它们,因此任何关于如何解决它们的指南或建议都会很棒,而不必依赖其他人来帮助解决它们。 目前我有一个关于如何解决它的建议,我们将不胜感激,但从长远来看,关于如何追踪问题原因的一般建议会更好。
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 出现的位置。
-
好吧,如果您试图引用一个为空的对象,并且该对象可以为空,请在访问之前检查它是否为空。如果对象永远不应该为空,那么您的代码中存在逻辑错误条件,需要找出原因。
-
您的代码似乎与您的问题无关。它们之间有什么联系?您是要我们为您调试吗?
-
最初我打算就问题所在寻求帮助,但问题在我写它时发生了变化,因为我不想依赖其他人来帮助我调试我的代码它会帮助我长期依赖他人调试。
标签: java nullpointerexception runtimeexception