java dev
java dev

Reputation: 29

How to create array in Java and check if contain zero to shift it to the most right?

I am creating a simple java code that ask user to create an array by interning elements to this array, than the code have a function that check if this array contain zeros it will traverse the zeros to the most right and to become the array like this: 1234000

this is my code

package testforarray;

import java.util.Arrays;
import java.util.Scanner;

public class test3 {

    public static void main(String[] args){

        int n = 0;
        int[] numbers = new int[8];
        Scanner scan = new Scanner(System.in);



        for (int  i = 0 ; i<numbers.length-1; i++){

            System.out.println("enter the number");

            numbers[i] = scan.nextInt();        
        }
        System.out.println(Arrays.toString(numbers));

        removeZeros(numbers);

     System.out.println(Arrays.toString(numbers));

    }


    public static void removeZeros(int[]arr){

        for (int i = 0 ; i< arr.length; i++){
            if(arr[i] ==0){
                int[]arr2 = new int[i];     
            }
            i--;
        }
    }
}

the program display the array without change anything.

Upvotes: 0

Views: 68

Answers (2)

Kostas Kryptos
Kostas Kryptos

Reputation: 4111

You can take advantage of the default value of 0 for arrays of integral types as this is guaranteed by the java language spec. So your array is already initialized with zeros. You can now only add the non-zero values, using a counter. eg

int nonZeroCounter = 0;
int current = 0;
for (int  i = 0 ; i < numbers.length-1; i++){
    System.out.println("enter the number");
    current = scan.nextInt();
    if (current!=0)
        numbers[nonZeroCounter++] = current;        
}

Upvotes: 0

sol4me
sol4me

Reputation: 15698

Currently you are not replacing anything in removeZeros method , Moreover there is no need to create a new array. You can simplify your code

 public static void replace (int[] arr) {
        int total = 0;
        int length = arr.length;
        for (int index = 0; index < length; index++)
            if (arr[index] != 0)
                arr[total++] = arr[index];
        Arrays.fill(arr, total, length, 0);
    }


Input : {1, 0, 0, 2, 0, 3, 5}
Output : [1, 2, 3, 5, 0, 0, 0]

Upvotes: 2

Related Questions