-2

thanks for looking. Lets get straight to the question.

So here is how my classes look

`

class Moon{
        double distance;
        double angle;
        double diameter;
        String col;
        double centreOfRotationDistance;
        double centreOfRotationAngle;
    }
class Planet{
        double distance;
        double angle;
        double diameter;
        String col;
        Moon moon = new Moon();
    }

`

However, when I am trying to access Planet[i].moon like this, java throws the NullPointerException. Did anything go wrong with my code? If yes, how can I fix it?

`

System.out.println("Creating planets...");
        String[] colArray = {"red", "orange", "yellow", "green", "blue", "indigo", "violet", "white", "red"};
        for(int i = 0; i < 8; i++){
            planets[i] = new Planet();
            planets[i].distance = 100 + (i * 100);
            planets[i].angle = 0 + (i * 20);
            planets[i].diameter = 20 + (i * 10);
            planets[i].col = colArray[i];
            System.out.println("Planet " + i + " created");
            System.out.println("Creating moon..." + i);
            planets[i].moon.distance = 10 + (i * 5);
            planets[i].moon.angle = 0 + (i * 20);
            planets[i].moon.diameter = i + 2;
            planets[i].moon.col = colArray[i++];
            planets[i].moon.centreOfRotationDistance = (100 + (i * 100))/10;
            planets[i].moon.centreOfRotationAngle = 0 - (i * 20);
        }
        System.out.println("Done creating planets.");
        System.out.println("Creating the sun...");

`

Stack, in case its useful

Thanks again for reading/answering

My original code was thisOriginal code

I thought I might be too ambitious to access a class that im creating and take values from there. Therefore i tried to change the code to the snippet above, however it didnt work?

Asked a few friends and no one had any idea why it went wrong. Thus posting

suk1
  • 5

1 Answers1

3

These lines are the problem:

planets[i].moon.col = colArray[i++];
planets[i].moon.centreOfRotationDistance = (100 + (i * 100))/10;

In the first of these lines, you're incrementing i - which means on the next line, planets[i] is referring to an array index where the element is still null.

I suspect that just this simple change will fix the problem:

planets[i].moon.col = colArray[i];

As a side note, I'd also suggest changing your code to create everything about the Planet once, then assign it into the array:

Planet planet = new Planet();
planet.distance = 100 + (i * 100);
planet.angle = 0 + (i * 20);
planet.diameter = 20 + (i * 10);
planet.col = colArray[i];
// etc
planets[i] = planet;

(I'd also recommend using private fields and probably a constructor accepting a bunch of the values, but that's a different matter.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194