0

I am trying to make a neural network for a reinforcement AI in Java 14, and I have the Main class and the AGENT class separate to improve readability. In the main() method, I create a new AGENT object like so on line 25:

AGENT agent = new AGENT();

and when I run the program, I expect to have the object created without an exception and run some function calls, but instead I get a NullPointerException:

Exception in thread "main" java.lang.NullPointerException
at com.company.AGENT.<init>(AGENT.java:19)
at com.company.Main.main(Main.java:25)

When I looked in the AGENT class to try and debug, I found line 19:

neural_network[j].add(new Node());

and I was confused, as neither the Node object, the neural_network variable, or the ArrayList contained inside of the neural_network array should have been null. I checked to see if there was a problem with my definition of the neural_network array:

private ArrayList<Node>[] neural_network = new ArrayList[5];

but the definition seemed okay. Finally I checked if adding a parameter to the definition of the ArrayList would help, or if removing the parameter from the typecast would help, upon doing which I got errors which terminated my program, instead of the runtime error I was getting from the NullPointerException. I am not sure where the null object is that is causing the issue.

To reproduce, create an object in the Main class inside of the main() method; inside the object's class, create a private variable with an array of ArrayLists which store a third object, and add new objects of the third type to the ArrayLists.

  • 2
    Do you realise that `new ArrayList[5]` is creating an array that can contain 5 `ArrayList`s? The array has 5 null elements. – Sweeper Aug 11 '20 at 04:13
  • 1
    This `ArrayList[] neural_network = new ArrayList[5];` only makes *room* for 5 ArrayLists; it doesn't create any. – Bohemian Aug 11 '20 at 04:19
  • Java naming conventions use camel-cased for most things other than constants. Variables and methods start with lower case (neuralNetworks). – NomadMaker Aug 11 '20 at 04:34

1 Answers1

1

You have initialized the array but not the elements of the array. In your AGENT constructor:

for (int i = 0; i < neural_network.length; i += 1) {
    neural_network[i] = new ArrayList<>();
}

before trying to add the Node.

Allen D. Ball
  • 1,916
  • 1
  • 9
  • 16