Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all the numbers 0 inside an array using another array [closed]

Tags:

java

arrays

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.

like image 522
Alex Avatar asked May 10 '26 07:05

Alex


1 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));
    }
}
like image 60
Michu93 Avatar answered May 11 '26 21:05

Michu93



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!