Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 数组nullpointerException错误_Java_Arrays_Nullpointerexception - Fatal编程技术网

Java 数组nullpointerException错误

Java 数组nullpointerException错误,java,arrays,nullpointerexception,Java,Arrays,Nullpointerexception,这是我的部分代码: `private Instrumento[] repInst; public RepositorioInstrumentos(){ Instrumento[] repInst = new Instrumento[20]; } private int getPos(int id){ int pos= -1; for(int i=0; i<tam; i++){ if (repInst[i]!=null&a

这是我的部分代码:

`private Instrumento[] repInst;
 public RepositorioInstrumentos(){
    Instrumento[] repInst = new Instrumento[20];
 }
 private int getPos(int id){
        int pos= -1;
        for(int i=0; i<tam; i++){
            if (repInst[i]!=null&&repInst[i].getId()==id){
                pos=i;
                i=tam;
            }
        }
        return pos;
    }`
repInst的所有位置都为空。我想,如果他把那个“if”放进去,他会跳过它,返回pos=-1


为什么不工作?

repInst在构造函数中是局部变量

private Instrumento[] repInst;
public RepositorioInstrumentos(){
 repInst = new Instrumento[20];
 }
private int getPos(int id){
    int pos= -1;
    for(int i=0; i<tam; i++){
        if (repInst[i]!=null&&repInst[i].getId()==id){
            pos=i;
            i=tam;
        }
    }
    return pos;
}
private Instrumento[]repInst;
公共存储设备(){
repInst=新仪器[20];
}
私有int getPos(int id){
int pos=-1;

对于(int i=0;i初始化构造函数中的
repInst
,然后访问它的方法,因为如果在未初始化它的情况下访问它的方法,您将得到
NullPointerException
,而
tam
变量的值是多少?它的值可能大于数组长度,那么它还将抛出
arrayindexoutofboundsXce期权

private Instrumento[] repInst;
 public RepositorioInstrumentos(){
   repInst = new Instrumento[20];
 }
 private int getPos(int id){
        int pos= -1;
        int tam=20;
//tam variable value should b less then arrays length
        for(int i=0; i<tam; i++){
            if (repInst[i]!=null&&repInst[i].getId()==id){
                pos=i;
                i=tam;
            }
        }
        return pos;
}`
private Instrumento[]repInst;
公共存储设备(){
repInst=新仪器[20];
}
私有int getPos(int id){
int pos=-1;
int-tam=20;
//tam变量值b应小于数组长度

对于(inti=0;i只需做一个更改。在构造函数外面初始化这个数组

Instrumento[] repInst = new Instrumento[20];

或者用它的对象初始化它。

好吧……如果
repInst
的所有位置都是
null
,那么就不会调用对位置
i
中包含的实例实际执行任何操作的逻辑。可能的情况是,自动装箱和
null
getId()有一些乐趣
。tam变量在哪里?为什么在构造函数中初始化新的Arraylist?甚至还没有初始化主变量。
Instrumento[] repInst = new Instrumento[20];