I've run into a strange instance of NullPointerExceptionwhere I run the following code,
Graph_img g = new Graph_img(3,4);
g.randomGraph();
where the constructor and method are the following,
public Graph_img(int width, int height){
super();
w = width;
h = height;
Node[][] Img = new Node[w][h];
}
//generate new MRF graph ~75% 0 bilevel
public void randomGraph(){
V = new ArrayList<Node>(0);
E = new ArrayList<Edge>(0);
for(int x=0; x<w; x++)
for(int y=0; y<h; y++){
if(Math.random()>0.75)
Img[x][y] = new Node(x*h+y,1,2); //<--- NullPointerException
else
Img[x][y] = new Node(x*h+y,0,2); //<--- NullPointerException
V.add(Img[x][y]);
}
}
But if I run with the initialization moved to the method instead of the constructor,
public Graph_img(int width, int height){
super();
w = width;
h = height;
//Node[][] Img = new Node[w][h]; <-- MOVING THIS
}
//generate new MRF graph ~75% 0 bilevel
public void randomGraph(){
V = new ArrayList<Node>(0);
E = new ArrayList<Edge>(0);
Node[][] Img = new Node[w][h]; //<-- MOVED HERE
for(int x=0; x<w; x++)
for(int y=0; y<h; y++){
if(Math.random()>0.75)
Img[x][y] = new Node(x*h+y,1,2);
else
Img[x][y] = new Node(x*h+y,0,2);
V.add(Img[x][y]);
}
}
Then everything works. I am perplexed - why? Thanks - Steve