Question:
I need to search for a number in an array. If the number is found in the list, remove it from the list by packing the array and fill the last element by 0.
Code:
import java.util.*; public class RemoveElement { public static void main(String[] args) { // create an array and populate it int[] array = {1,2,3,4,5,6,7,8,9,10}; System.out.println(Arrays.toString(array)); // this will be the int to be removed from the array int x = 3; System.out.println("Removing: " + x); // here is where the work is done: for(int i=0; i<array.length; i++) { if(array[i]==x){ // remove x and shift everything for(int j=i; j<array.length-1; j++){ array[j] = array[j+1]; } // fill last element with a zero array[array.length-1]=0; } } System.out.println(Arrays.toString(array)); } }
Output:
$ java RemoveElement [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Removing: 3 [1, 2, 4, 5, 6, 7, 8, 9, 10, 0]