我的代码是这样的:
public class Foo {
public int a;
Bar[] bar = new Bar[10];
a = bar[0].baz;
}
public class Bar {
public int b;
public Bar () { //I tried doing away with this constructor, but that didn't
//fix anything
b = 0;
}
public int Baz () {
//do somthing
}
}
我收到类似于以下内容的错误消息:
Exception in thread "Foo" java.lang.NullPointerException
在 Foo 中的任何一行,我都尝试调用 Bar 类的任何函数或值。如何防止 bar[] 为空?
编辑:经过一番摆弄,我终于把它修好了,谢谢大家!但是,我无法调用构造函数来解决问题;我必须创建另一个函数并从 Main 调用该函数(在我的情况下,类 Foo 实际上是类 Main,如果这真的很重要的话)。我的最终结果:
public class Foo {
public int a;
Bar[] bar = new Bar[10];
public Foo () { //this constructor wasn't called for some reason... I checked this
//by using System.out.println... no message was print onscreen
for (int a = 0; a < bar.length; a++)
bar[a] = new Bar();
}
public static void initializeFoo () {
for (int a = 0; a < bar.length; a++)
bar[a] = new Bar();
}
public static void Foo () {
initializeFoo();
a = bar[0].baz;
}
}
有人想帮我解决这个问题,还是我应该提出另一个问题?:)