I’m new to java, and I’m currently programming a pacman as a class project. The game is played on an array[8][8]; I’ve got to read a .txt file that includes walls, ghosts and their position in the array, and show them there. I’ve used Scanner, StringTokenizer and nextInt. When I compile the file, it doesn’t give any errors, but when running it, java.lang.ArrayIndexOutOfBoundsException: 8 shows up; by the error name I can infer there’s some object outside the array, but I can’t seem to identify which one. Here’s the code:
public class JuegoPacman
{
private Elemento _mat[][];
public JuegoPacman()
{
}
public void Escanear() throws FileNotFoundException
{
Scanner sc=new Scanner(new File("inicio.txt"));
while(sc.hasNext())
{
String token = sc.next();
if (token.equals("Pared"))
{
int i=sc.nextInt() -1;
int j=sc.nextInt() -1;
_mat[i][j] = new Pared(i,j);
}
else if(token.equals("Fantasma"))
{
int i=sc.nextInt();
int j=sc.nextInt();
_mat[i][j]= new Fantasma(i,j);
}
}
}
public void crearMatriz()
{
for (int i=0; i<_mat.length;i++)
{
for (int j=0;i<_mat[i].length;j++)
{
System.out.print(_mat[i][j]);
}
}
}
public void jugar() throws FileNotFoundException
{
_mat=new Elemento[8][8];
Escanear();
crearMatriz();
}
}
This is the main class:
public class Aplicacion {
public Aplicacion()
{
}
public static void main(String[] args) throws FileNotFoundException
{
JuegoPacman juego = new JuegoPacman();
juego.jugar();
}
}
And here’s the .txt i’m trying to read:
Pared 2 2
Pared 3 2
Pared 4 2
Pared 6 2
Pared 7 2
Pared 5 4
Pared 2 5
Pared 4 5
Pared 6 5
Pared 2 6
Pared 4 6
Pared 6 6
Pared 2 7
Pared 5 7
Fantasma 1 3
Fantasma 1 8
Fantasma 8 8
In advance, Thank you very much.
EDIT:
Substracting 1 of each of the location numbers still gives me the same error.
ERROR:
nullnullFantasma@a31e1bnullnullnullnullFantasma@10da5ebException in thread “main” java.lang.ArrayIndexOutOfBoundsException: 8
at JuegoPacman.crearMatriz(JuegoPacman.java:58)
at JuegoPacman.jugar(JuegoPacman.java:67)
at Aplicacion.main(Aplicacion.java:22)
The numbering arrangements in java start from zero. If you create an array of 8 positions, then the positions will be from 0 to 7. If you try to find position 8, it will give you that error.
what to do to fix your code is
must be replaced on both sides