Java beginner here getting non zero numbers

Viewed 2228

I just want to ask why the temp in my method NonZeros does not change its elements even though I explicitly assign each element of temp whenever the source has a nonzero element. Here's my work.

package nonzeros;
public class NonZeros {
    public static void main(String[] args) {
        int [] B = {0,1,2,3,2};
        int [] newone = NonZeros(B);
        for(int q = 0; q < newone.length; q++){
            System.out.println(newone[q]);
        }
    }
    public static int[] NonZeros(int [] A){
        int [] temp = new int[4];
        for(int i = 0; i < A.length;i++){
            if(A[i] != 0){
                int j = 0;
                temp[j] = A[i];
                j++;
            }
        }
        return temp;
    }
}

Here's the result: run: 2 0 0 0

However, the result should be: 1 2 3 2

4 Answers

Step one, count the non zero values. Step two, create the new array. Step three, fill it with non-zero values like

public static int[] NonZeros(int[] A) {
    int count = 0;
    for (int i = 0; i < A.length; i++) {
        if (A[i] != 0) {
            count++;
        }
    }
    int[] temp = new int[count];
    int p = 0;
    for (int i = 0; i < A.length; i++) {
        if (A[i] != 0) {
            temp[p++] = A[i];
        }
    }
    return temp;
}

Alternatively, use a lambda and filter like

public static int[] NonZeros(int[] A) {
    return Arrays.stream(A).filter(i -> i != 0).toArray();
}

You declare int j=0; inside the loop, so all assignments go to the same place.

You need to move the j index outside of the loop:

public static int[] NonZeros(int [] A){
    int [] temp = new int[4];
    int j = 0;
    for (int i=0; i < A.length; i++) {
        if (A[i] != 0) {
            temp[j] = A[i];
            j++;
        }
    }
    return temp;
}

The reason why your current output happens to be [2, 0, 0, 0] is that the final element in the input array is 2, and gets written to the first entry in the output array. In fact, currently all values are being written to the first entry of the output array.

The scope of the "j" variable that you are defining is the if block that contains it because you are declaring it inside the condition which results in you overwriting the first element in your temp array each time you find a non-zero number in the source while the rest of your temp elements remain unchanged. The solution is to move the declaration of "j" to the body of the method just before the loop, that is:

public static int[] NonZeros(int [] A){
int [] temp = new int[4];
int j = 0;
for(int i = 0; i < A.length;i++){
    if(A[i] != 0){
        temp[j] = A[i];
        j++;
    }
}
return temp;
}
Related