java - 二维数组的奇怪错误

标签 java arrays multidimensional-array 2d

我是一名java初学者,我遇到了一个我认为非常奇怪的错误。这是我运行程序时出现的错误:

java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
at test.mob.<init>(mob.java:14)
at test.test.<clinit>(test.java:21)
Exception in thread "main" Java Result: 1

我在 NetBeans 中编程,错误没有显示在 IDE 中,仅在运行程序时显示。这是我的 mob 类的代码,看看你是否能找到问题。

package test;

public class mob {
    int counter = 0;
    int[][] mob;
    int loopCount = 0;
    int loopCount2 = 0;

    public mob(){
    //0: x pos
    //1: y pos

     mob = new int[counter][1];
     mob[counter][0]=test.width;         
     mob[counter][1]=test.height/2;
     counter++;
}
public void mobLoop(){
    while(loopCount <=counter){
        while(loopCount2<2){
        mob[loopCount][0]--;
        loopCount2++;
        }
        loopCount2 = 0;
        loopCount++;
    }
    return;
    }

}

最佳答案

Java 中数组是从零开始索引的。您正在创建一个大小为 [0][1] 的数组,该数组在第一维中包含零个元素,在第二维中包含一个元素。因此,当您尝试访问此行上的数组时:

mob[counter][1]=test.height/2;

你在两个维度上都超出了界限。根据我看到的代码,您需要向两个维度添加 1 以保留边界。

关于java - 二维数组的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18603230/

相关文章:

java - 每次迭代后删除二维数组的列和行

javascript - javascript 的 mxgraph 示例中的 GraphEditor 中的 java 代码负责什么功能?

java - "This method is deprecated as the user should use the Java 5 conventions."这是什么意思?

c - 如何从 char[][] 写入文件?

c++ - 使用什么数据结构来存储游戏对象的基于 2D 单元的 map ?

python - 从 Python : passing list of numpy pointers 调用 C

php - 基于数组在mysql表中添加多行

java - 何时何地调用 EventQueue.invokeLater() 方法

Java 输入流比输出流更快

Javascript - 按键/值顺序排列到 JSON