0

The arrays don't get initialized and I'm not understanding why.

So this is the first class

class Bag{
    Potato[] potatoes = new Potato[10]; //so we have 10 bags of potatoes
}

which cointains an array of this class

class Potato{
     int numb;
     public void setNumb(int numb){
         this.numb = numb;
     }
     String[] facts = new String[numb];//every potato has    a numb of facts
}

I created the object Bag so i assumed it contains an array of the class Potato, which contains an array of String facts, but they aren't initialized even tho: "String[] facts = new String[numb]"

public class test{
public static void main (String[ ] args){
    Bag newBag = new Bag();
    newBag.potatoes[0].setNumb(2);
    newBag.potatoes[0].facts[0]="firstFact";
    System.out.println(newBag.potatoes[0].facts[0]);
}
}

the error:

Exception in thread "main" java.lang.NullPointerException
user207421
  • 305,947
  • 44
  • 307
  • 483
Nino Klajnsek
  • 29
  • 1
  • 5
  • The facts array will always have size 0 since numb will always be 0 when the array is created. Note that it's created *before* the constructor is called. Be sure to create the array **within the constructor**. Declare it in the class, yes, but initialize it in the constructor. – Hovercraft Full Of Eels Mar 20 '16 at 22:28
  • Even if I delete the atribute numb, and size the array at 10, create the array in the contrsutor, still the same problem. – Nino Klajnsek Mar 20 '16 at 22:34
  • You also need to create a Potato instance for each Potato in the potatoes array, using a for loop. – Hovercraft Full Of Eels Mar 20 '16 at 22:43
  • For example, please have a look at this question and answer to a similar problem: http://stackoverflow.com/questions/20057412/java-null-pointer-exception-with-static-array – Hovercraft Full Of Eels Mar 20 '16 at 22:48

0 Answers0