我想加載兩個機器人在二維陣列中的初始位置,它們由字母N,S,O,E表示。這段代碼爲什麼會產生一個NullPointerException?
以下代碼無法正常工作。爲什麼?
static Point[] robotInitialPositions(char [][]inputMatrix){
Point [] helperArray = new Point[2];
int aux=0;
for (int i=0; i<(inputMatrix[0].length-1); i++)
for (int j=0; j<(inputMatrix[0].length-1); j++)
{
if((inputMatrix[i][j]=='N')||(inputMatrix[i][j]=='S')||(inputMatrix[i][j]=='O')||(inputMatrix[i][j]=='E'))
{
helperArray[aux++]= new Point(i,j);
}
}
System.out.println("helper array 1: i,j " + helperArray[1].i + ", " + helperArray[1].j);
//NullPointerException here
return helperArray;
}
全碼:
package bfs_robots;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
class Point {
int i;
int j;
Point(int i, int j){
this.i=i;
this.j=j;
}
}
public class Main {
static char turnCounter (char orientation){
if(orientation=='N')
return 'O';
if(orientation=='O')
return 'S';
if (orientation=='S')
return 'E';
else
return 'N';
}
static char turnClock(char orientation){
if(orientation=='N')
return 'E';
if(orientation=='E')
return 'S';
if (orientation=='S')
return 'O';
else
return 'N';
}
static Point[] robotInitialPositions(char [][]inputMatrix){
Point [] helperArray = new Point[2];
int aux=0;
for (int i=0; i<(inputMatrix[0].length-1); i++)
for (int j=0; j<(inputMatrix[0].length-1); j++)
{
if((inputMatrix[i][j]=='N')||(inputMatrix[i][j]=='S')||(inputMatrix[i][j]=='O')||(inputMatrix[i][j]=='E'))
{
helperArray[aux++]= new Point(i,j);
}
}
System.out.println("helper array 1: i,j " + helperArray[1].i + ", " + helperArray[1].j);
return helperArray;
}
static void bfs_find_solution (char[][] inputMatrix){
int countOfMovements=0;
// each turn and displacement adds one
// when moved N,S,D and O must be replaced with .
// * indicates wall, invalid movement
Point robotInitial[] = robotInitialPositions(inputMatrix);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File("input.txt")));
char [][] inputMatrix;
String line;
char [] lineAsCharArray;
int matrixSize;
while(true){
line = br.readLine();
matrixSize=Integer.parseInt(line);
inputMatrix = new char [matrixSize][matrixSize];
if (matrixSize==0){ // end outer looping
break;
}
else { //begin inner looping
for (int i=0; i<matrixSize; i++){
line = br.readLine();
inputMatrix[i] =line.toCharArray();
}
bfs_find_solution(inputMatrix);
}
}
}
}
input.txt中(0表示文件的結束)
5
D....
N...S
.....
*...*
....D
5
.....
S..S.
.....
.....
D..D.
3
SN.
***
.DD
0
哪條線給NPE? – CoolBeans 2011-05-01 20:35:30
以上代碼中的行號是否是指向的異常? – MeBigFatGuy 2011-05-01 20:35:35