Pregunta

Aceptar lo estoy consiguiendo un ArrayIndexOutOfBoundsException. No sé por qué.

Aquí está mi código:

/**
Tile Generator
Programmer: Dan J.
Thanks to: g00se, pbl.
Started May 23, 2010
**/

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class tileGen extends Applet implements KeyListener  {


    Image[] tiles; // tile arrays
    Image player; // player image
    int x, y, px, py, tx, ty; // x tile - y tile // player x - player y // tile x - tile y
    boolean left, right, down, up, canMove; // is true?
    int[][] board; // row tiles for ultimate mapping experience!
    final int NUM_TILES = 33; // how many tiles are we implementing?
    Label lx, ly; // to see where we are!
    private static int BLOCKED = 28;

    int lastX, lastY, row, col;

  public void init() {

    board = loadBoard();

    tiles = new Image[NUM_TILES];
    for(int i = 0;i < NUM_TILES;i++) {
        tiles[i] = getImage(getClass().getResource(String.format("tiles/t%d.png", i)));
    }
        board[2][2] = BLOCKED;
        player = getImage(getClass().getResource("player.png")); // our player
        addKeyListener(this);
        canMove = true;
        px = 0;
        py = 0;
        lastX = 0;
        lastY= 0;
    }

    public void keyPressed(KeyEvent e) {

if (blocked(lastX,lastY) == true) {
    System.out.println("You were JUST on a BLOCKED tile!");
}

int x1 = lastX = lastX + 1;
int y1 = lastY;
       System.out.println("++++++++++++++++++++++++\n(" +x1+","+y1+") " + blocked(x1,y1) + "\n++++++++++++++++++++++++");

        if (e.getKeyCode() == KeyEvent.VK_LEFT) {
            left = true;
            px = px - 32;
            lastX = lastX - 1;
        }
        if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
            right = true;
            px = px + 32;
            lastX = lastX + 1;
        }
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            down = true;
            py = py + 32;
            lastY = lastY + 1;
        }
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            up = true;
            py = py - 32;
            lastY = lastY - 1;
        }



        repaint();
    }
public void keyReleased(KeyEvent e){} // ignore
public void keyTyped(KeyEvent e){} // ignore

  public void paint(Graphics g) {


        for (row = 0; row < board.length; row++) {
            for (col = 0; col < board[row].length; col++) {
                int index = board[row][col];
                g.drawImage(tiles[index], 32 * col, 32 * row, this);

            }
        }
        System.out.println("X: " + lastX + "\nY: " + lastY + "\n=============================\n");

System.out.println("Blocked tile?: " +blocked(lastX,lastY) + " ("+lastX + ","+lastY+")");
        g.drawImage(player, px, py, this);
    } // end paint method

     public void update(Graphics g)
     {
          paint(g);
     }

    public int[][] loadBoard() {
        int[][] board = {
                { 2,2,24,24,24,24,24,1,3,0,0,0 },
                { 2,2,24,23,23,23,24,1,3,0,0,0 },
                { 1,1,24,23,23,23,24,1,3,3,3,3 },
                { 1,1,24,24,23,24,24,1,1,1,1,1 },
                { 1,1,1,1,7,1,1,1,1,1,3,3 },
                { 5,1,1,1,7,7,7,7,7,1,3,3 },
                { 6,1,3,1,1,1,1,1,7,7,7,3 },
                { 6,1,3,1,3,1,3,1,1,1,7,3 }
            };
    return board;
    }

    public boolean blocked(int tx, int ty) {

            return board[tx][ty] == BLOCKED;
        }

} // end whole thing

La cosa es que cuando voy a la de ladrillo rojo en board[2][2] ... voy allí. Luego subo ... entonces trato de ir a dar marcha atrás, pero que el error aparece. También cuando voy a la derecha 8 plazas ... también tengo ese error.

también, fingir mi mapa 2D es dividida en cuatro cuadrados ... así un cuadrado es la parte superior izquierda ... si voy a ningún otro sitio ... me sale ese error.

¿Qué estoy haciendo mal? Gracias.

Actualización: He encontrado el culpable! Es la LASTx y actualizaciones Lasty cuando se presiona la tecla! Pero todavía no puedo averiguar para fijar esta matriz fuera de los límites! : (

Aquí está el error: Exception in thread "AWT-EventQueue-1" java.lang.ArrayIndexOutOfBoundsException: 8 at tileGen.blocked(tileGen.java:111) at tileGen.paint(tileGen.java:86) at tileGen.update(tileGen.java:92) at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239) at sun.awt.RepaintArea.paint(RepaintArea.java:216) at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:306) at java.awt.Component.dispatchEventImpl(Component.java:4706) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre ad.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread. java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre ad.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)

    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)

    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)</code>
¿Fue útil?

Solución

En términos generales, un ArrayIndexOutOfBoundsException se produce cuando hay un intento de acceder a un elemento de matriz en un índice que está fuera de límites.

A continuación se muestra fragmento de algunos escenarios (independientes el uno del otro) donde se lanzan ArrayIndexOutOfBoundsException:

    // 1
    int[] x = new int[5];
    x[-1] = 0; // ArrayIndexOutOfBoundsException: -1

    // 2
    int[] x = new int[5];
    x[5] = 0; // ArrayIndexOutOfBoundsException: 5

    // 3
    int[][] table = new int[3][3];
    table[0][10] = 0; // ArrayIndexOutOfBoundsException: 10

    // 4
    int[][] table = new int[3][3];
    table[-10][10] = 0; // ArrayIndexOutOfBoundsException: -10

    // 5
    int[][][][] whoa = new int[0][0][0][0];
    whoa[0][-1][-2][-3] = 42; // ArrayIndexOutOfBoundsException: 0

    // 6
    int[][][][] whoa = new int[1][2][3][4];
    whoa[0][1][2][-1] = 42; // ArrayIndexOutOfBoundsException: -1

¿Dónde y cómo esto sucede en el applet no está clara, pero puede estar seguro de que pasa por la razón correcta: usted ha intentado acceder ilegalmente a un elemento de matriz en un índice no válido, y dado que las matrices se verificaron con destino a Run- tiempo en Java, se eleva la excepción de tiempo de ejecución.

Es posible que desee llevar a cabo el depurador para ver cómo se evaluó el índice no válido, pero si no otra cosa, un montón de System.out.println donde quiera que el índice de mutación y donde quiera que está a punto de acceso a un elemento de matriz puede ayudar a localizar el insecto.


Otros consejos:

En lugar de:

lastX = lastX + 1;
lastY = lastY - 1;

Puede hacer:

lastX++;
lastY--;

Esto se llama el "post-incremento" y "operadores de decremento posterior". Utilizarse con prudencia, puede mejorar la legibilidad.

Referencias

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top