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 this
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