minorThreat minorThreat - 22 days ago 10
Java Question

How to properly instantiate a bi-dimensional array in Java

I am having problems on how to instantiate bi-dimensional array of objects. I tried to demonstrate below a small sample to reproduce the error I am getting.

I have this class named Node that basically stores one character. This class is used inside the class named Test as a bi-dimensional attribute. I used some user input to establish the size of the array and instantiate it inside the instantiate() method. Then, I try to populate the map using a set method. However, the compiler gives me the following error message:

Eclipse Console Output:


Exception in thread "main" java.lang.NullPointerException
at Test.populate(Main.java:44)
at Main.main(Main.java:77)


My input was:


Enter height:
3
Enter width:
3


Below is the code I am using to reproduce this error:

Class Node:

class Node {
private char content;

Node(){
this.content = ' ';
}

Node(Node node){
this.content = node.getContent();
}

//Setter
public void setContent(char c) {
this.content = c;
}

//Getter
public char getContent() {
return this.content;
}
}


Class Test:

class Test {
private Node[][] map;
private int height, width;

public void instantiate(){
Scanner reader = new Scanner(System.in);
System.out.println("Enter height: ");
this.height = reader.nextInt();
System.out.println("Enter width: ");
this.width = reader.nextInt();
map = new Node[height][width];
reader.close();
}

public void populate(){
for(int i=0;i<height;i++)
for(int j=0;j<width;j++){
if((i+j) %2 == 0)
map[i][j].setContent('a');
else
map[i][j].setContent('b');
}
/*
* a b a b
* b a b a ...
* a b a b
* b a b a
* . . .
*/
}

public void print(){
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
System.out.print(map[i][j].getContent());
}
System.out.println();
}
}

public Node[][] getMap(){
return this.map;
}

}


Main method:

public class Main {

public static void main(String[] args) {
Test testing = new Test();
testing.instantiate();
testing.populate();
testing.print();
}
}


The code can also be seen here: http://pastebin.com/agFMmB38

I am still getting used to Java (coming from C++), so they have some differences that I couldn't figure it out yet.

Any help would be greatly appreciated.
Thank you!

Answer

map[i][j] needs to be set to a new object, like map[i][j] = new Node('a') (well, if you had a constructor in Node which worked like that: it would be written Node(char a) { this.content = a; }).

You cannot do map[i][j].setContent('a') because it is not a preexisting Node object.