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
4
  • 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. Commented Mar 20, 2016 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. Commented Mar 20, 2016 at 22:34
  • You also need to create a Potato instance for each Potato in the potatoes array, using a for loop. Commented Mar 20, 2016 at 22:43
  • For example, please have a look at this question and answer to a similar problem: stackoverflow.com/questions/20057412/… Commented Mar 20, 2016 at 22:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.