Not an ArrayList. An Array. For some reason, my teacher (or rather, the lesson plan we are using) requires that we make a program that takes an array of integers and removes all the zeroes. So far I have:
public void remove(int index) {
for(int i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
}
public void compact() {
readFile();
System.out.print("Before: ");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
for(int i = 0; i < array.length; i++) {
if(array[i] == 0) {
remove(i);
}
}
System.out.print("After: ");
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
However the output is:
Before: 0 94 12 21 3 0 0 34 26 44 55 0 32 0 0 0 0 0 0 0 0 0 0 0 0
After: 94 12 21 3 0 34 26 44 55 32 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
When it should be more like:
Before: 0, 9, 7, 0, 0, 23, 4, 0
After: 9, 7, 23, 4
I made all the errors in the output green so you don't have to weed them out.
Also, since I didn't comment it, I want to point out that remove() basically moves all the vales of the array once to the right if an undesired value is found (in this case, 0). I have determined that the error with the lone zero in the second line occurs because the remove() function simply moves all the values (including the second 0) to the right, and the second zero doesn't get checked. Does anyone have a solution for this?
And I need to find a way to remove all those trailing zeros without simply not printing them.
The readFile() function in compact() is there because the numbers of the array are supposed to come from a file.
The actual assignment can be found here.