I created the ArrayDriver and ArrayClass1 classes to gain some experiences working with arrays and array elements. The code in ArrayDriver is suppose to:
1) Create an array of ArrayClass1 objects.
2) Initialize the two attributes of each array element to 0 and print this information out.
3) Modify each array element's attribute and print out the modified array element's attributes.
I encountered a Nullpointerexception error while compiling the ArrayDriver class with Eclipse. I read that this error occurs when a pointer is dereferenced but has not been instantiated (java - What is a Null Pointer Exception? - Stack Overflow). I created an array and initialized every array element with the first for loop. Still, I cannot correct the problem.
public class ArrayDriver { public static void main(String[] args){ int ARRAY_LENGTH = 10; ArrayClass1 [] alpha = new ArrayClass1[ARRAY_LENGTH]; //Declares and instantiates the ArrayClass1 array called alpha for(int i = ARRAY_LENGTH-1; i-1>=0; i--){ //Initializes the attributes of each alpha array element (both x and y) to 0 alpha[i].x = 0; alpha[i].y = 0; } for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Print out what is initialized System.out.println("Old Array["+i+"]x: "+alpha[i].x); System.out.println("Old Array["+i+"]y: "+alpha[i].y); } for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Modifies each array element's attributes alpha[i].x = i; alpha[i].y = i+1; } for(int i = ARRAY_LENGTH-1; i-1 >= 0; i--){ //Prints out new attributes System.out.println("New Array["+i+"]x: "+alpha[i].x); System.out.println("New Array["+i+"]y: "+alpha[i].y); } } }
Array Class:
public class ArrayClass1 { public int x = 0; public int y = 0; public ArrayClass1(int x, int y){ this.x = x; this.y = y; } }