我有一个试图打印2维数组的问题,我不断地在printArray()和printArray()的第一个for循环中得到一个空指针异常。我确实知道什么是虚假的感觉,我只是很难理解为什么我会得到它。在尝试打印数组之前,我遇到过这个问题,最后我会很好地理解这一点。空指针异常 - 打印二维数组
import java.lang.*;
import java.util.*;
public class Board {
int N = 3;
static int [][] unittest;
//construct a board from an N-by-N array of blocks
//(where blocks[i][j] = block in row i, column j)
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
//Random r = new Random(); uses blocks[i][j] = r.nextInt();
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
blocks[i][j] = randInt(0,9);
}
}
unittest = blocks.clone();
}
//generates random numbers in a range
private static int randInt(int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
//board size N
public int size(){
return 0; //placeholder
}
//number of blocks out of place
public int hamming(){
return 0; //placeholder
}
//sum of manhattan distances between blocks and goal
public int manhattan(){
return 0;
}
//is this board the goal board?
public boolean isGoal(){
return true; //placeholder
}
//is the board solvable?
public boolean isSolvable(){
return true; //placeholder
}
//does this board equal y?
//Object because can only take objects
//does it use Comparable?
public boolean equals(Object y){
return true; //placeholder
}
//all neighboring boards
public Iterable<Board> neighbors(){
Stack<Board> placeholder = new Stack<Board>();
return placeholder;
}
//string representation of the board
public String toString(){
return "placeholder";
}
//unit test
private static void printArray(){
for (int i = 0; i < unittest.length; i++){ //**NULL POINTER EXCEPTION
for (int j = 0; j < unittest[i].length; j++){
System.out.print(unittest[i][j]);
if (j < unittest[i].length - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args){
//prints out board
printArray(); //**NULL POINTER EXCEPTION
}
}
初始化你有一个关闭数组你需要作出一个实例你的班级的关键字'new'。做到这一点主要。这样你的变量'unittest'将是非空的,因为你的类的构造函数是'unittest'的填充。 – csmckelvey 2014-10-08 03:18:30