[英]Java - Instantiate an object with array as parameter
我在Cassette类中通过参数有此构造函数:
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中实例化Cassette类的一些对象,以测试分配给我的某些函数。 在我的一生中,我无法找到正确的方法而又没有得到null.Pointer.Exception
这些是我的主行:
//...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];}
或者,您也需要在for循环中使用int[]
之前对其进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.