-3

I have no problem compiling however when i execute the code i get this error :

Exception in thread "main" java.lang.NullPointerException
at Stock.enregistrer(Stock.java:25)
at TestStock.main(TestStock.java:13) 

I am learning java and i am stucked with this error for a while now . Thanks for the help.

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]);
    }
  } 
}
Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68

3 Answers3

1

You have to initialize your arrays in your constructor:

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

1024 is just an example for the size of the arrays. You should implement either resizing of the arrays or bound checking.

Tobias
  • 7,723
  • 1
  • 27
  • 44
0

It seems that you are using uninitialized variables. By doing:

Produit [] pdt ; 
Fournisseur [] four;
int [] qte ; 
int t = 0;

Your are not initializing the objects, you should do for example:

Stock(int number) {
    pdt=new Produit[number]  
    ...
}

This, usually gets inside the constructor, and when you incentiate the object you use:

Stock stock=new Stock(100); //100 is the number of array objects
user2279268
  • 21
  • 1
  • 1
  • 4
0

You are trying to use all the arrays which are not allocated. All of them must be allocate d in the constructor if you know their maximum size (let it be MAX_SIZE):

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

Otherwise, if you don't know its maximum size or if you just want to save memory you can reallocate them in enregistrer() function each time you call it:

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++ ;
}
Michael
  • 1,505
  • 14
  • 26