So, I am doing an assignment in a first-year CompSci class, and this array assignment is a little beyond me. I have worked with arrays and arraylists a bit in the past week or two, and for the most part i've been successful, but this assignment is giving me a class (TestArrays) that holds integer arrays, and is asking me to write the code for a class that creates arrays of that TestArrays object. Here is the code I was provided:
public class TestArrays
{
private int[] testArray;
public TestArrays()
{
testArray = new int[10];
generateRandomArray();
}
public void generateRandomArray()
{
for(int index = 0; index < testArray.length; index++)
{
testArray[index] = (int)(Math.random()*10 +1);
}
}
public int[] getArray()
{
return testArray;
}
And here is the code that I have attempted to write:
import java.util.ArrayList;
public class TestArrayLists
{
private ArrayList<TestArrays> testArrayList;
/**
* Complete the contructor for the class. Instantiate the testArrayList
* and call the fillArrayList method to add objects to the testArrayList.
* @param numElements The number of elements in the ArrayList
*/
public TestArrayLists(int numElements)
{
fillArrayList(numElements);
}
/**
* Complete the fillArrayList method. It should fill the testArrayList with
* TestArrays ojects consisting of 10 element int Arrays of random numbers.
* @param numElements The number of elements in the ArrayList
*/
private void fillArrayList(int numElements)
{
TestArrays testArray;
for(int i = 0; i < numElements; i++)
{
testArray = new TestArrays();
testArrayList.add(testArray);
}
}
/**
* For each TestArrays object in the testArrayList,
* print out the numbers in the int Array.
*/
public void printArrayList()
{
for(int i = 0; i < testArrayList.size(); i++)
{
System.out.println(testArrayList.get(i));
}
}
}
I get a null pointer exception when I try to run fillArrayList(), which I know means that I didn't instantiate the testArray properly, but the testArray constructor is supposed to do that (i think) and nothing that I have tried has worked.
I would prefer if you didn't just give me the code that I need to do this right, because although i'm sure its an easy fix that I am just not far enough to know about, I would prefer to know how to do this for the future as well. If you would be willing to explain to me what you're doing, I would really appreciate it. Thank you for time.