0

I am trying to add a class to an array and I get Exception in thread "main" java.lang.NullPointerException in my addAstronaut class.

package gov.nasa.spacevehicles;

import gov.nasa.personnel.Astronaut;

public class SpaceStation {

//private members
   private String name;
   private double stationWeight;
   private double altitude;

private Object[] Astronauts;
private int totalAstronauts;

//overloaded constructor
public SpaceStation(String name, double weight) {
   int altitude = 0;
   int totalAstronauts = 0; 
}

//method
public void addAstronaut(String name, double height, double weight) {
     Astronauts[0] = new Astronaut(); // Exception in thread
     Astronauts[1] = new Astronaut();
     Astronauts[2] = new Astronaut();

    
     stationWeight = stationWeight + weight;  
 }
sean jon
  • 15
  • 5
  • 1
    Because`Astronauts` array is not initialized. That's why it is null. – Chetan Sep 28 '20 at 01:53
  • Think of it this way; `Astronauts[0]` accesses the first element of the array that the `Astronauts` variable references. But `Astronauts` doesn't reference any array yet; you left it blank. So the compiler throws an exception because your code doesn't mean anything; you're asking the compiler to do an impossible task. – Charlie Armstrong Sep 28 '20 at 01:58

1 Answers1

0

You need to initialize the Astronauts array. Try something like:

Astronauts = new Object[10];

in the constructor for SpaceStation, take the size of the array as an input to that constructor, or use an ArrayList for variable size lists.

BeyondPerception
  • 534
  • 1
  • 6
  • 10