I’m working on a project for class where I am asked to take a .txt file, aggregate the data into distinct objects, then sort that list based on shared characteristics. My instructions are to make the program able to import up to 200 lines of text.
I have successfully implemented the program to import the .txt file, given a defined array size (if the .txt file has 6 lines, an array of 6 elements) but I need to be able to define it up to 200 elements. When going beyond the number of actual elements, say 6, it throws a NullPointerException. I can’t seem to find where this may be occurring as my code appears, at least visually, to handle any instance in which that may occur. Here is where the problem is occurring:
public Solid[] solids;
public int length;
public Measurer m;
public int h;
public SolidList(int size) {
length = 0;
solids = new Solid[size];
}
public void addSorted(Solid foo, Measurer m) {
int k = 0;
if (length != 0) {
while ((k < length) && foo.greaterThan(solids[k], m))
++k;
for (int j = length; j > k; --j)
solids[j] = solids[j - 1];
}
solids[k] = foo;
++length;
}
Specifically, Eclipse is encountering the NullPointerException in the while loop in addSorted(...). This only happens if the array does indeed have null elements, but I suppose I can’t figure out how to prevent the method from trying to access null elements.
Might solve the problem. But you should really look into using Collections (look at ArrayList) to handle collections/arrays of dynamic input length.