Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java beginner here getting non zero numbers

Tags:

java

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

like image 464
Elo Avatar asked Sep 09 '26 00:09

Elo


1 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();
}
like image 112
Elliott Frisch Avatar answered Sep 11 '26 13:09

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!