我的代码是这样的:
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; } }
有人想帮我解决这个问题,还是我想创造另一个问题?
精彩评论