Removing all the numbers 0 inside an array using another array

Viewed 123

I am having troubles solving this exercise: I have to remove all the numbers 0 inside my array. For example:

if my array has these values [18,17,0,16,0,5]
this must be my otput => [18,17,16,5]

This is what I have done:

import java.util.Scanner;
public class awz{

    public static int [] readArray (int [] n, int size){
        Scanner input = new Scanner(System.in);
        int i = 0;
        int [] container = new int[i];
        for( int j = 0;  j < size;  j++ )
            {
                System.out.println("Insert numbers"); 
                n[j] = input.nextInt();
                if( n[j] != 0 )
                container[i++] = n[j]; //Line 13
        }
        return container;
    }
    
    public static void main (String[]args){
        Scanner input = new Scanner(System.in);
        System.out.println("choose the size of your array");
        int arraySize = input.nextInt();
        int[] arrayElements = new int[arraySize];
        int [] cleanedArray = readArray(arrayElements,arraySize);   //Line 23    
    }
}

The compiler does not respond with errors, but when I am giving the input to write the single values of my array, a message in the terminal appears and the program crashes:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
   at awz.readArray(awz.java:13)
   at awz.main(awz.java:23)

Can you help me correcting my mistake, please? Keep in mind I am new to programming and this should be, more or less, the method to solve the exercise, I know there are functions that make the exercise much easier, but the teacher won't accept other solutions.

3 Answers

The cleanest way to do it is use streams:

    public class RemoveZeros {
    public static void main(String[] args){
        int[] array = new int[]{0,1,2,3,0,10};

        int[] newArrayWithoutZeros = Arrays.stream(array)
                .filter(number -> number != 0)
                .toArray();
        System.out.println(Arrays.toString(newArrayWithoutZeros));
    }
}

If the existing code should be kept as is, the issues in readArray method need to be addressed:

  • Count non-zeroes while reading the array from user input
  • Fix creation of container array
  • Copy non-zeros to container
public static int[] readArray (int[] n, int size) {
    Scanner input = new Scanner(System.in);
    int nonZeros = 0;
    for (int i = 0;  i < n.length;  i++) {
        System.out.println("Insert numbers"); 
        n[i] = input.nextInt();
        if (n[i] != 0) {
            nonZeros++;
        }
    }
    int[] container = new int[nonZeros];
    int z = 0;
    for (int i = 0; i < n.length; i++) {
        if (n[i] != 0) {
            container[z++] = n[i];
        }
    }
    return container;
}

However, it would be better to separate reading the input array and filtering 0s into different methods/functions.


Using Stream API makes this task trivial:

public static int[] removeZeroes(int[] arrWithZeroes) {
    return Arrays.stream(arrWithZeroes)
                 .filter(x -> x != 0)
                 .toArray();
}

Using lists, based on removeAll.

Integer[] container = { 18, 17, 0, 16, 0, 5 };
List<Integer> nonzeroList = new ArrayList<>(Arrays.asList(container));
nonzeroList.removeAll(Arrays.asList(0)); // nonzeroList - {18,17,16,5}
container = nonzeroList.toArray(new Integer[0]); // container - [18,17,16,5]
Related