Java Applet - ArrayIndexOutOfBoundsException

发布于 2024-09-03 07:44:09 字数 4946 浏览 13 评论 0原文

好的,我收到了 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 个方格时...我也收到该错误。

另外,假装我的二维地图被分成四个方块……好吧,第一个方块是左上角……如果我去其他任何地方……我会得到这个错误。

我做错了什么?谢谢。

更新:我找到了罪魁祸首!当我按下该键时,这是最后一次更新和最后一次更新!但我仍然不知道如何修复这个数组越界! :(

这是错误: 线程“AWT-EventQueue-1”中出现异常 java.lang.ArrayIndexOutOfBoundsException: 8 在tileGen.blocked(tileGen.java:111) 在tileGen.paint(tileGen.java:86) 在tileGen.update(tileGen.java:92) 在 sun.awt.RepaintArea.updateComponent(RepaintArea.java:239) 在 sun.awt.RepaintArea.paint(RepaintArea.java:216) 在 sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:306) 在java.awt.Component.dispatchEventImpl(Component.java:4706) 在 java.awt.Container.dispatchEventImpl(Container.java:2099) 在 java.awt.Component.dispatchEvent(Component.java:4460) 在 java.awt.EventQueue.dispatchEvent(EventQueue.java:599) 在 java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre 广告.java:269) 在 java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread. 爪哇:184) 在java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre 广告.java:174) 在 java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)

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

    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)</code>

OK so I am getting an ArrayIndexOutofBoundsException. I don't know why.

Here's my code:

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

The thing is when I go to the red brick at board[2][2]... I go there. Then I go up... then I TRY go to back down but that error pops up. Also when I go to the right 8 squares... I ALSO get that error.

ALSO, pretend my 2d map is split into FOUR squares... well square one is the top left... if I go ANYWHERE else ... I get that error.

What am I doing wrong? Thanks.

update: i found the culprit! It's the lastX and lastY updates when I press the key! But I still can't figure out to fix this array out of bounds! :(

Here is the 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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白馒头 2024-09-10 07:44:09

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

以下代码段显示了抛出 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访问数组元素可以帮助定位bug。


附加提示:

代替:

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

您可以这样做:

lastX++;
lastY--;

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

参考文献

Generally speaking, an ArrayIndexOutOfBoundsException is thrown when there's an attempt to access an array element at an index that is out of bounds.

The following snippet shows some scenarios (independent of each other) where ArrayIndexOutOfBoundsException are thrown:

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

Where and how this happens in your applet is unclear, but rest assured that it happens for the right reason: you've illegally tried to access an array element at an invalid index, and since arrays are bound-checked at run-time in Java, the run-time exception is raised.

You may want to bring out the debugger to see how the invalid index was evaluated, but if nothing else, lots of System.out.println wherever you're mutating the index and wherever you're about to access an array element can help locate the bug.


Additional tips:

Instead of:

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

You can do:

lastX++;
lastY--;

This is called the "post-increment" and "post-decrement" operators. Used judiciously, it can improve readability.

References

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文