-2

Possible Duplicate:
objects classes and arrays - why is it returning ‘null’ ? [java]

The other questions with similar titles all have the answer that their data needs to be initialized which I have done but I'm still getting a null pointer exception. Could anyone tell me why?

    public class grid{
private Node [][] board = new Node [9][9];

public boolean add(int x, int y, char label) {
    boolean valid=true;

    System.out.println("enter add");
    if(label==' '){
        System.out.println("enter if 1");
        board[x][y].setValue('0');
    }
    else if(label<='9'&&label>'0'){
        System.out.println("enter if 2");
        board[x][y].setValue(label);
    }
    else{
        valid=false;
    }
    if(valid)
        System.out.println("valid");
    return valid;
}

I'm getting the error on the setValue Lines (10 and 14)

    public class Node{
public char value;
public char []  possibleValues = {1,2,3,4,5,6,7,8,9};
public boolean correct=false;
    }

Edit: I figured it out, if anyone else has the same problem, this seems to fix it.

    if(label==' '){
        System.out.println("enter if 1");
        board[x][y]= new Node(' ');
    }
    else if(label<='9'&&label>'0'){
        System.out.println("enter if 2");
        board[x][y]= new Node(label);
    }
3
  • Your char array should be public char [] possibleValues = {'1','2','3','4','5','6','7','8','9'}; Your code might not even complie. Commented Jan 19, 2013 at 19:17
  • 1
    @smit - It will compile just fine, it just won't do what he thinks. A char in java is simply a 16bit signed integer. Using single quotes gets the value for a given character from the default character map. (e.g. '1' == 49 if you're using UTF-8 ) Commented Jan 19, 2013 at 19:19
  • @BrianRoach +1 Yes you are right.. Commented Jan 19, 2013 at 19:32

1 Answer 1

1

An array does not initialize the elements of the array. So, each board[x][y] will be initially null.

Sign up to request clarification or add additional context in comments.

4 Comments

Oh, what is this doing then? private Node [][] board = new Node [9][9];
@Iweir - Not what you think. See the duplicate of this question I linked to, or the tutorial on arrays docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Okay, the thing is for this I'll be using directing input so I don't know the values until a file is given. I'm a bit confused on how I would initialize it then.
Nevermind I figured it out and I'll update the OP

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.