用Java

时间:2015-10-18 20:13:37

标签: java arrays initialization instantiation

我对java比较陌生,这是我第二次尝试设计一个包含类对象数组的程序。我遇到了麻烦,因为当我进入调试模式时,它向我显示阵列正在正确构建。但是,当我尝试构建一个字符串甚至打印到控制台时,我得到一个空指针异常。

我正在尝试创建一个Slot类对象数组。

public class C {
int slotNum;
Slot[] s;


public C(int byteSize, int slotNum){
    this.slotNum = slotNum;

    Slot[] s = new Slot[slotNum]; //create an array of slots

    for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
        s[i] = new Slot(byteSize); 
    }
    display();
}

Slot类有自己的数组block [],由通过其构造函数传入的值构造。

public class Slot {

boolean v;
short block[];

public Slot(int byteSize){
    valid = false;

    //Instantiate each element in block[] to 0
    short block[] = new short[byteSize];
    for(int i = 0; i < block.length; i++){
        block[i] = 0;
    }
}

稍后在程序中,我尝试打印到控制台或构建一个字符串,当我尝试使用C类的slot []中的任何元素时,它总是会中断。

我是否正确地实例化并初始化了我的2个不同数组?

3 个答案:

答案 0 :(得分:1)

public class C {
int slotNum;
Slot[] s;


public C(int byteSize, int slotNum){
this.slotNum = slotNum;

s = new Slot[slotNum]; //create an array of slots

for(int i = 0; i < slotNum; i++){ //for every slot and instantiate
    s[i] = new Slot(byteSize); 
}
display();
}

尝试这样的事情

public class Slot {

boolean v;
short block[];

public Slot(int byteSize){
valid = false;

//Instantiate each element in block[] to 0
block = new short[byteSize];
for(int i = 0; i < block.length; i++){
    block[i] = 0;
}
}

答案 1 :(得分:1)

替换

short block[] = new short[byteSize];

block = new short[byteSize];

答案 2 :(得分:0)

始终使用 this 运算符在构造函数中初始化,以便您可以清楚地区分局部变量和实例变量

public Slot(int byteSize){
    valid = false;

    //Instantiate each element in block[] to 0
    this.block = new short[byteSize];
    for(int i = 0; i < block.length; i++){
        block[i] = 0;
    }
}