线程“main”中的异常java.lang.NullPointerException(

时间:2013-11-03 20:57:46

标签: 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 ; 
  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]);
    }
  } 
}

3 个答案:

答案 0 :(得分:1)

您必须在构造函数中初始化数组:

Stock() {
  pdt = new Produit[1024];
  four = new Fournisseur[1024];
  qte = new int[1024];
}

1024只是数组大小的一个例子。您应该实现数组的大小调整或绑定检查。

答案 1 :(得分:0)

您似乎正在使用未初始化的变量。 通过做:

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

答案 2 :(得分:0)

您正在尝试使用未分配的所有阵列。如果你知道它们的最大大小(让它是MAX_SIZE),它们都必须在构造函数中分配d:

Stock() {
  Produit [] pdt = new Produit[MAX_SIZE];
  Fournisseur [] four = new Fournisseur[MAX_SIZE];
  int [] qte = new int[MAX_SIZE];
}

否则,如果你不知道它的最大大小,或者你只是想节省内存,你可以在每次调用它时在enregistrer()函数中重新分配它们:

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++ ;
}