I thought this was pretty simple, because I am pretty sure I have done it before, but I cant seem to get this to work.
My class is:
public class City
{
String start = null;
String end = null;
int weight = 0;
}
and I am doing:
City cityGraph[] = new City[l];
When I try to access cityGraph[x].start for example, I get a null pointer exception, so I figured I need to initialize every element in the array as well, so I do:
for(int j = 0; j < l; j++)
{
cityGraph[j] = new City();
}
but it is giving me this error:
No enclosing instance of type Graphs is accessible.
Must qualify the allocation with an enclosing instance
of type Graphs (e.g. x.new A() where x is an instance of Graphs).
I have no idea what this means, or how to fix it. Any help would be appreciated!
That can happen when you have declared
public class Cityas an inner class ofpublic class Graphslike soThis way the
Citycannot be constructed without constructing aGraphsinstance first.You’d need to construct the
Cityas follows:This makes honestly no sense. Rather either extract the
Cityinto a standalone class,or make it a static nested class by declaring it
static.Either way, you’ll be able to construct a new
Cityby justnew City().See also: