“线程中的异常”;“主要”;java.lang.NullPointerException(
我在编译时没有问题,但是当我执行代码时,会出现以下错误:“线程中的异常”;“主要”;java.lang.NullPointerException(,java,Java,我在编译时没有问题,但是当我执行代码时,会出现以下错误: Exception in thread "main" java.lang.NullPointerException at Stock.enregistrer(Stock.java:25) at TestStock.main(TestStock.java:13) 我正在学习java,这个错误困扰了我一段时间。谢谢你的帮助 public class Stock { Stock() { } Produit [] pdt ;
Exception in thread "main" java.lang.NullPointerException
at Stock.enregistrer(Stock.java:25)
at TestStock.main(TestStock.java:13)
我正在学习java,这个错误困扰了我一段时间。谢谢你的帮助
public class Stock {
Stock() {
}
Produit [] pdt ;
Fournisseur [] four;
int [] qte ;
int t = 0;
void enregistrer(Produit p , Fournisseur f , int q) {
pdt[t] = p ;
four[t] = f ;
qte[t] = q ;
t++ ;
}
void afficher() {
for (int i = 0 ; i < pdt.length ; i++) {
System.out.println("Le produit "+pdt[i].getNomP()+"à pour fournisseur : "+four[i].getNomEnt()+" et la quantité est de "+qte[i]);
}
}
}
公共类股票{
股票(){
}
Produit[]pdt;
Fourniseur[]四;
int[]qte;
int t=0;
无效注册(产品p、Fourniseur f、int q){
pdt[t]=p;
四[t]=f;
qte[t]=q;
t++;
}
无效附加项(){
对于(int i=0;i
您必须在构造函数中初始化数组:
Stock() {
pdt = new Produit[1024];
four = new Fournisseur[1024];
qte = new int[1024];
}
1024只是数组大小的一个示例。您应该实现数组大小调整或绑定检查。您似乎在使用未初始化的变量。 通过这样做:
Produit [] pdt ;
Fournisseur [] four;
int [] qte ;
int t = 0;
您没有初始化对象,您应该执行以下操作,例如:
Stock(int number) {
pdt=new Produit[number]
...
}
这通常会进入构造函数内部,当您激励您使用的对象时:
Stock stock=new Stock(100); //100 is the number of array objects
您正在尝试使用所有未分配的数组。如果您知道它们的最大大小(设为MAX_size),则必须在构造函数中分配所有数组: 否则,如果您不知道其最大大小,或者您只是想节省内存,则可以在每次调用时在Enregister()函数中重新分配它们:
void enregistrer(Produit p , Fournisseur f , int q) {
/* resize pdt array */
Produit[] pdt_new = new Produit[t+1];
System.arraycopy(pdt, 0, pdt_new, 0, t);
pdt_new[t] = p;
pdt = null; // not actually necessary, just tell GC to free it
pdf = pdt_new;
/********************/
/* the same operation for four array */
Fournisseur[] four_new = new Fournisseur[t+1];
System.arraycopy(four, 0, four_new, 0, t);
four_new[t] = f;
four = null;
four = four_new;
/********************/
/* the same operation for qte array */
int[] qte_new = new int[t+1];
System.arraycopy(qte, 0, qte_new, 0, t);
qte_new[t] = q;
qte = null;
qte = qte_new;
/********************/
t++ ;
}
请正确缩进代码。
void enregistrer(Produit p , Fournisseur f , int q) {
/* resize pdt array */
Produit[] pdt_new = new Produit[t+1];
System.arraycopy(pdt, 0, pdt_new, 0, t);
pdt_new[t] = p;
pdt = null; // not actually necessary, just tell GC to free it
pdf = pdt_new;
/********************/
/* the same operation for four array */
Fournisseur[] four_new = new Fournisseur[t+1];
System.arraycopy(four, 0, four_new, 0, t);
four_new[t] = f;
four = null;
four = four_new;
/********************/
/* the same operation for qte array */
int[] qte_new = new int[t+1];
System.arraycopy(qte, 0, qte_new, 0, t);
qte_new[t] = q;
qte = null;
qte = qte_new;
/********************/
t++ ;
}