Java - 实例化以数组作为参数的对象



我的盒式磁带类中有这个参数构造函数:

public class Cassette {
private int cass_Num;
private String cass_Titre;
private String cass_Realisat;
private int nbCopie;
private int [] cass_Emprunteur;
//...code
public Cassette(int num, String titre, String real, int copies, int[] nbEmp){
    this.cass_Num = num;
    this.cass_Titre = titre;
    this.cass_Realisat = real;
    this.nbCopie = copies;
    for(int i=0;i<nbEmp.length;i++){this.cass_Emprunteur[i] = nbEmp[i];}
}
//set methods...
//get methods...
}//end

我想在我的 Main 中实例化盒式磁带类的一些对象,以测试我的作业的一些函数。对于我的生活,我无法找到正确的方法来做到这一点而不会得到空。指针异常

这些是我的主线中的行:

//...code
Cassette [] tabCas = new Cassette[MAX_CASSETTES];
for(int i=0;i<tabCas.length;i++){tabCas[i]= new Cassette();}
tabCas[0] = new Cassette(0001,"Jurassic Pork","Steven Swineberg",7,new int[] {11111,44444});    //<--- error here
//...code

感谢您的帮助!

看看你的构造函数 "this.cass_Emprunteur" 是空的,你尝试使用 this.cass_Emprunteur[i] 访问

Cassette 构造函数中,您需要:

cass_Emprunteur = nbEmp;

而不是行:

for(int i=0;i<nbEmp.length;i++){this.cass_Emprunteur[i] = nbEmp[i];}

或者,您需要先初始化int[],然后再在 for 循环中使用它。

最新更新