So i have this array of objects and i want to initialize it so when i use the objects accessor functions it wont throw me nullpointerexceptions when the user doesnt input enough data to fill every element of the array.
Here is the code, the array im talking about is planetArray:
import java.util.*;
public class SolarSystem{
public static final int PLANET_MAX = 10;
public int planetCount = 0;
Planet[] planetArray = new Planet[PLANET_MAX];
String systemName;
public SolarSystem(String name){
this.systemName = name;
}
}
public void addPlanet(String planetName, double planetMass, double planetDistance){
double mass = Math.round(planetMass*1000)/1000.0;
double distance = Math.round(planetDistance*1000)/1000.0;
Planet newPlanet = new Planet(planetName, mass, distance);
newPlanet.calculatePeriod(planetDistance);
planetArray[planetCount] = newPlanet;
planetCount++;
}
public String toString(){
String myString = systemName + "\n";
for(int i = 0; i < PLANET_MAX; i++){
String name = planetArray[i].getPlanetName();
double mass = planetArray[i].getPlanetMass();
double distance = planetArray[i].getPlanetDistance();
double period = planetArray[i].getPlanetPeriod();
if(period <= 1){
period = period * 365.25;
period = Math.round(period*1000)/1000.0;
myString = myString + "Planet " + name + " has a mass of " + mass + " Earths, is " + distance + "AU from its star, and orbits in " + period + " days\n";
}
else{
period = Math.round(period*1000)/1000.0;
myString = myString + "Planet " + name + " has a mass of " + mass + " Earths, is " + distance + "AU from its star, and orbits in " + period + " years\n";
}
}
return myString;
}
//accessors
public Planet[] planetArray(){
return planetArray;
}
public String getSystemName(){
return systemName;
}
//mutators
public void setPlanetArray(Planet[] planetArray){
this.planetArray = planetArray;
}
public void setSystemName(String systemName){
this.systemName = systemName;
}
}
If i use a for loop to try and cycle through the array to use the mutator functions to set values for the objects i get nullpointerexceptions back. If the array is not fully populated i get nullpointerexceptions. Its a big requirement that users are able to enter data into the array until they decide they are done. How do i set the whole array to a value that wont throw me these exceptions?
edit:an example would be:
public SolarSystem(String name){
this.systemName = name;
for(int i = 0; i < PLANET_MAX; i++)
planetArray[i].setPlanetName("/0");
}
}
I want to be able to set the planet names to null but trying to do anything just gets nullpointerexceptions.