I want to load the initial positions of two robots in a bidimensional array, they are indicated by the letters N,S,O,E.
The following code ain’t working. Why?
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;
}
Full code:
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 indicates the end of file)
5
D....
N...S
.....
*...*
....D
5
.....
S..S.
.....
.....
D..D.
3
SN.
***
.DD
0
Seems wrong.
The first line should be inputMatrix.length-1
Also the “<” should be “<=” I think. Or keep the “<” and don’t have the “length-1”, instead just “length”