【发布时间】:2013-01-19 19:02:33
【问题描述】:
可能重复:
objects classes and arrays - why is it returning ‘null’ ? [java]
其他标题相似的问题都有我已经完成的需要初始化他们的数据的答案,但我仍然得到一个空指针异常。谁能告诉我为什么?
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;
}
我在 setValue 行(10 和 14)上遇到错误
public class Node{
public char value;
public char [] possibleValues = {1,2,3,4,5,6,7,8,9};
public boolean correct=false;
}
编辑:我想通了,如果其他人有同样的问题,这似乎可以解决它。
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);
}
【问题讨论】:
-
你的 char 数组应该是
public char [] possibleValues = {'1','2','3','4','5','6','7','8','9'};你的代码甚至可能无法编译。 -
@smit - 它会编译得很好,只是不会按照他的想法去做。 Java 中的
char只是一个 16 位有符号整数。使用单引号从默认字符映射中获取给定字符的值。 (例如,如果您使用的是 UTF-8,则为 '1' == 49) -
@BrianRoach +1 是的,你是对的..
标签: java multidimensional-array 2d