私のコードは次のようなものです:
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 []がnullになるのを防ぐにはどうすればよいですか?
編集:少しいじった後、私はついにそれを修正しました、みんなに感謝します!ただし、コンストラクターを呼び出して修正することはできませんでした。別の関数を作成し、その関数を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;
}
}
誰かがそれで私を助けたいですか、それとも私は別の質問を作成することになっていますか?:)