0

i have an array of objects, i want to add objects in this array using a method named "AddProd()" .but in order to add in the right case of the array i have to know where the first empty case in the array is . this is the Add Method :

  public void AddProd(Produit p){

    int notempty = 0;
    int i = 0;
    while(produits[i] != null){
        notempty++;
        i++;
    }

    if (notempty < 49) {
        produits[notempty + 1] = p;
    }
}

let me explain to you first i have a while loop that checks where the first null case is. the while loop keeps incrementing (i++) till it finds an empty case . the problem is when i run i get two errors :

Exception in thread "main" java.lang.NullPointerException
    at prosit.pkg2.v1.pkg0.Magasin.AddProd(Magasin.java:27)
    at prosit.pkg2.v1.pkg0.main.main(main.java:22)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

this is (Magasin.java:27) : while(produits[i] == null){ i think that the comparaison to null is not correct and the second error is when i call the method in the main class . Any solutions please and thanks .

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
CoderTn
  • 985
  • 2
  • 22
  • 49
  • That just suggests that `produits` is null. Although even if it's not null, you're going to get an `ArrayIndexOutOfBoundsException` at some point - you need to use `produits.length`, or an enhanced for loop. – Jon Skeet Sep 29 '18 at 06:39

1 Answers1

0

Problem is you haven't initialized the array produits, itself is null.