我是新來的java,我目前正在編寫一個pacman作爲一個類項目。遊戲在數組上進行[8] [8];我必須閱讀一個.txt文件,其中包括牆,鬼和它們在陣列中的位置,並在那裏顯示它們。我使用過Scanner,StringTokenizer和nextInt。當我編譯文件時,它不會給出任何錯誤,但是在運行它時,java.lang.ArrayIndexOutOfBoundsException:8顯示出來;通過錯誤名稱,我可以推斷出陣列外有一些對象,但我似乎無法確定哪一個。下面的代碼:創建一個數組給我java.lang.ArrayIndexOutOfBoundsException
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();
}
}
這是主類:
public class Aplicacion {
public Aplicacion()
{
}
public static void main(String[] args) throws FileNotFoundException
{
JuegoPacman juego = new JuegoPacman();
juego.jugar();
}
}
而這裏就是我試圖讀取.TXT:
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
在進步,非常感謝你。
編輯:每個位置號碼的
從其減去1仍然給我同樣的錯誤。
ERROR: nullnullFantasma @ a31e1bnullnullnullnullFantasma @ 10da5ebException在線程 「主要」 java.lang.ArrayIndexOutOfBoundsException:在JuegoPacman.jugar(JuegoPacman.java:67)在JuegoPacman.crearMatriz(JuegoPacman.java:58) 在Aplicacion.main(Aplicacion.java:22)
仍然給我同樣的錯誤 – Jmdjorgeek 2012-02-12 02:01:18
@Jmdjorgeek必須更換兩側 – Jhonathan 2012-02-12 02:14:16
感謝您的糾正 – Jmdjorgeek 2012-02-12 02:36:10