was curious on how to write a method to remove all zeros from an array. If I have the array in the main method. for example my Main Method would look something like
public static void main(String[] args) {
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
System.out.println(Arrays.toString(test) + ": length = " + test.length);
int[] result = removeZeros(test);
System.out.println(Arrays.toString(result) + ": length = " + result.length);
}
and have the code output the length and the array without the zeros like:
[1, 0, 4, 7, 0, 2, 10, 82, 0]: length = 9
[1, 4, 7, 2, 10, 82]: length = 6
I don't know how to write a method for this other than doing something like this:
int[] test = {1, 0, 4, 7, 0, 2, 10, 82, 0};
int length = 0;
for (int i=0; i<test.length; i++){
if (test[i] != 0)
length++;
}
int [] intResult = new int[length];
for (int i=0, j=0; i<test.length; i++){
if (test[i] != 0) {
intResult[j] = test[i];
j++;
}
}
any ideas how to make this a method and have it print out both the original array and the new array without zeros in it + the length?
public int[] removeZeros(int[] input) {}