gpt4 book ai didi

java - 尝试在方法中访问三角形数组时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 11:03:02 25 4
gpt4 key购买 nike

每次我尝试使用 tarray[i][j] 时,我在尝试使用一种方法单独访问我的三角形数组时遇到问题我得到一个空指针异常,除非它是在类创建中完成的,例如我有一个 get 方法并使用了 return tarray[0][0]即使它在创作中打印得很好,它也会向我抛出错误。

我知道我可能做了一些愚蠢的事情,但我就是想不通,

public class Triangular<A> implements Cloneable
{

private int inRa;
private A [][] tarray;

/**
* Constructor for objects of class Triangular
* @param indexRange - indices between 0 and indexRange-1 will be legal to index
* this a triangular array
* @throws IllegalArgumentException - if indexRange is negative
*/
public Triangular(int indexRange) throws IllegalArgumentException
{
inRa=indexRange;
int n = inRa;
int fill = 1;
Object [][] tarray = new Object [inRa + 1][];
for (int i = 0; i <= inRa; i++){
tarray[i] = new Object [n];

}

for (int i = 0; i < tarray.length; i++){

for (int j = 0; j + i < tarray[i].length; j++){
tarray[i][j + i] = fill;
fill ++;
}
}

for (int i = 0; i < tarray.length; i++) {
for (int j = 0; j + i < tarray[i].length; j++){
System.out.print(tarray[i][j + i] + " ");
}
System.out.println();

}

}
}

感谢您的帮助!

最佳答案

您无需在构造函数中对 tarray field 初始化任何内容,而是初始化同名的局部变量;这个:

Object [][] tarray = new Object [inRa + 1][]; // doesn't access the tarray field

但是,您必须向 tarray 字段分配一些内容才能修复 NPE。

顺便说一句:最好不要使用与字段同名的局部变量。

关于java - 尝试在方法中访问三角形数组时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com