-1

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.

  • 3
    Possible duplicate of [How to check if array element is null to avoid NullPointerException in Java](http://stackoverflow.com/questions/425439/how-to-check-if-array-element-is-null-to-avoid-nullpointerexception-in-java) – Robert Moskal Dec 07 '15 at 04:08
  • That should give you what you need. – Robert Moskal Dec 07 '15 at 04:08
  • Problem is the answer to that one only shows someone manually entering data into a known array size. I want to populate the array with null values or 0's or something without knowing the size of the array and doing it manually. – Luke Wheeldon Dec 07 '15 at 04:17
  • Consider using a list instead, if the array size is unknown. In the for-loop you can check for null: `if (planetList.get(i) != null) do stuff`. – dabo248 Dec 07 '15 at 04:20

2 Answers2

0

It's the same thing. you

for(int i = 0; i < PLANET_MAX; i++) {   
    if(planetArray[i]==null) 
        continue;
    planetArray[i].setPlanetName("/0");
}

The other commentor is right, lists are more convenient for this sort of thing.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
0

Looking at this from a stylistic, common-practices viewpoint, you really don't want to do what you suggest. Namely, virtually no one inserts a non-null dummy object or value to indicate 'not set yet' or 'not provided'.

The java null is used almost exclusively to mean 'unset', 'not provided' or 'not appropriate for this use. To invent a new mechanism will muddy the intent of your code and may cause havoc down the road if anyone else uses your code.

While it does seem arduous to check for nulls all the time, Java best-practices dictate that:

  1. If an obj is not null, it is a valid obj ready for use and incorporation within your cacluation, operation, view, use queries, etc.

  2. You sanitize any input from users, uploads, CGI params, anything out of your control. Any invalid or missing values become null so as not to interfere with the rest of your program.

  3. It's even a good idea to chech params and values for null if they are called from components outside of your control or that you have not thoroughly inspected or excersized.

These practices can dramatically improve the security, reliability, and longevity of your code. Sorry for the verbose 'answer'.

TSnyder
  • 437
  • 4
  • 6