0

所以,我一直在思考为什么我的代码整晚都没有工作,经过多年无药可救的搜索,我决定在这里发帖。我收到了一条 NPE:

this.numbers[a][b] = new Integer(n[a][b]);

这是我的完整代码:

private int[][] numbers, temp, temp2;
private int a, b;

public Matrix(int[][] n)
{
System.out.println(n[0].length);
int numbers[][] = new int[n[0].length][n[1].length];
int temp[][] = new int[n[0].length-1][n[1].length-1];
int temp2[][] = new int[n[0].length][n[1].length];
    for(a=0;a<n[0].length;a++)
        for(b=0;b<n[1].length;b++)
        {
            this.numbers[a][b] = new Integer(n[a][b]);
            this.temp2[a][b] = new Integer(n[a][b]);
        }
    this.xLength = n[0].length;
    this.yLength = n[1].length;
}

我不知道为什么会出错;虽然我确信这是一个简单的错误。帮助表示赞赏。(n[][] 是一个完美的数组)

4

2 回答 2

2

numbers is an array that is defined inside your method, not inside the class you have, so this.numbers refers to the array that you have defined inside your class (which admittedly has the value null), not the local numbers array you have defined in your method.

于 2012-12-26T03:15:49.093 回答
0

我马上就注意到了:在你的构造函数中,你屏蔽了你的三个实例变量numbers,temptemp2. 你不需要这样做。

从每个变量中删除类型声明和方括号,您的 NPE 不应继续。它主要发生是因为numbersis null,并且您不能取消引用/索引为 null。

中也没什么意义new Integer(n[a][b]);。如果n[i]and的类型numbers[j][k]int[](即原语int),那么您不需要进行任何自动装箱;只需直接分配值。

您的循环变量 ( a, b) 必须int在它们前面,然后它们才能按照您期望的方式工作 - 否则它们不会被声明。

最后,您正在循环错误的维度。对于在长度不同的二维数组上循环,您希望使用n.length外循环和n[0].length内循环。所以它看起来像这样:

 for (int a = 0; a < n.length; a++) {
    for (int b = 0; b < n[0].length; b++) {
        numbers[a][b] = new Integer(n[a][b]);
        temp2[a][b] = new Integer(n[a][b]);
    }
}
于 2012-12-26T03:24:04.413 回答