0

There's something I'm missing here. with this code I get a java.lang.NullPointerException:

public static void main(String[] args) {

    Board board = new Board();
    board.Initialise();

}


public class Board {

private Obj[][] tableau;

public void Board() {

    tableau = new Obj[8][8];    
}

public void Fill_Board() {

    tableau[0][0]= new Obj('B');
    }
}

But with this other code I get no error. What I am doing wrong, and how to initialize properly this array of object?

public class Board {

private Obj[][] tableau = new Obj[8][8];

public void Board() {

}

public void Fill_Board() {

    tableau[0][0]= new Obj('B');
    }
}
2
  • 1
    I think you need to provide us more context because you have a class Tab but you don't use it in main() Commented Apr 2, 2012 at 17:39
  • @TerraNova993 Why are you unformatting the edits people made to make your code readable? Commented Apr 2, 2012 at 17:41

2 Answers 2

2

Board() ends up being a member function and not a constructor, and therefore never gets called. The problem is the void keyword, which needs to be removed:

public Board() { /* removed the `void' */
    tableau = new Obj[8][8];    
}
Sign up to request clarification or add additional context in comments.

4 Comments

@Makoto: There clearly is (Board board = new Board()). What we're presented with is a snippet, and I suspect the fact that Board() seems to appear in Tab -- and not in Board -- is just an artefact of this being a snippet.
I really don't get the downvotes. I am starting to regret investing time into trying to help out.
sorry for this, this is just a snippet actually, I edited the code to rename the class properly.
Now it's right. At first there was no Board class. That's why you got my downvote. Now you got an upvote.
0

I get no error when I run this code (changing Obj to an actual class), perhaps you can provide a more concrete example with a main method of what you're trying to do?

If you're looking at making a constructor then it needs to be the same name as your class, i.e. Tab and have no return type.

So you would need to add:

public Tab() {
    // initialization code here
}

You're constructor will run whenever you create a new instance of that class. You want to use it to initialize all of your variables.

Tab t = new Tab(); // Constructor runs

Edit:

You're main method uses class Board but you have given us a class called Tab. I can assume that you really want class Board so you should change all Tab to Board in the above example, if that's what you're looking for.

1 Comment

thnaks, the problem was the constructor had void in it so I deleted void to create a proper constructor and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.