My code looks something like this:
public class Foo {
public int a;
Bar[] bar = new Bar[10];
a = bar[0].baz;
}
public class Bar {
public int b;
public Bar () {
b = 0;
}
public int Baz () {
}
}
And I get an error like this:
Exception in thread "Foo" java.lang.NullPointerException
on any line in Foo, I'm trying to call any function or value of the Bar class. How to prevent bar [] from being null?
EDIT: After some attempts, I finally fixed them, thanks everyone! However, I could not call the constructor to fix the situation; I had to create another function and call this function from Main (in my case, the Foo class is actually the Main class, if that really matters). My end result:
public class Foo {
public int a;
Bar[] bar = new Bar[10];
public Foo () {
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;
}
}
Anyone want to help me with this, or should I create another question? :)
source
share