【问题标题】:Java Applet - ArrayIndexOutOfBoundsException [duplicate]Java Applet - ArrayIndexOutOfBoundsException [重复]
【发布时间】:2011-02-25 15:07:39
【问题描述】:

好的,所以我得到了一个 ArrayIndexOutofBoundsException。我不知道为什么。

这是我的代码:

/**
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

问题是当我去board[2][2] 的红砖时...我去那里。然后我上去......然后我尝试退后但弹出错误。此外,当我走到右边的 8 个方格时......我也得到了那个错误。

另外,假设我的 2d 地图被分成四个正方形......好吧,一个正方形是左上角......如果我去任何其他地方......我得到那个错误。

我做错了什么?谢谢。

更新:我找到了罪魁祸首!当我按下键时,它是 lastX 和 lastY 更新!但我仍然无法解决这个数组越界! :(

这是错误: 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)

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

    在 java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

【问题讨论】:

  • 你需要告诉我们你从哪一行得到错误等等。
  • 好的,我更新了主要问题。
  • int x1 = lastX = lastX + 1; 你为什么在这里做lastX = lastX + 1?看起来异常发生在blockedtx == 8
  • 我也不确定错误的确切来源,但您可能希望确保您已弄清楚所有坐标系。二维数组是array[row][col],Java 中的图形是(col, row),原点在左上角,y 轴倒置。我看到您对Graphics.drawImage 的调用正确地命令colrow,但不能完全确定其他xy 是否做正确的事。
  • 这很有趣.. 我不能越过 board[-1][-1] 例如 board[-2][-2] :(

标签: java arrays applet indexoutofboundsexception


【解决方案1】:

一般来说,当尝试访问超出范围的索引处的数组元素时,会抛出 ArrayIndexOutOfBoundsException

下面的 sn-p 展示了一些抛出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

这在您的小程序中发生的位置和方式尚不清楚,但请放心,它发生的原因是正确的:您非法尝试访问无效索引处的数组元素,并且由于数组在运行时受到边界检查-在 Java 中,会引发运行时异常。

您可能想调出调试器来查看无效索引是如何评估的,但如果没有其他问题,无论您要更改索引还是要访问数组元素,大量 System.out.println 都会有所帮助找到错误。


其他提示:

代替:

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

你可以这样做:

lastX++;
lastY--;

这称为“后增量”和“后减量”运算符。明智地使用它可以提高可读性。

参考文献

【讨论】:

  • 附加附加提示:Java 类以大写字母开头。
  • 另外,正确缩进代码。请。
  • 我无法越过 board[-1][-1] 例如 board[-2][-2] :(
  • @Dan:我不明白你在说什么,但数组索引必须是非负数 (java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.4)
  • 我明白了!我解决了这个问题。我正在重新定义 lastX 和 lastY + 1 。 :P
猜你喜欢
  • 2016-08-31
  • 2014-08-31
  • 2013-04-06
  • 1970-01-01
  • 2011-03-30
  • 2011-03-22
  • 1970-01-01
  • 2015-11-08
  • 2014-11-17
相关资源
最近更新 更多