Programmatically implements the given array, removing items with a value of 0 in the array into a new array.
Package com.liaojianya.chapter1;/** * This program demonstrates the "the" to remove-zero from-old array and insert into new Array. * @author LIAO Jianya * July 21, 2016 */public class Removezero{public static void Main (string[] args) {int k = 0;int Oldarra Y[] = {1, 3, 4, 5, 0, 0, 0, 8, 4, 5, 0, 9, 1}; System.out.println ("------------print Oldarray--------------"), for (int i:oldarray) {System.out.print (i + ""); if ( Oldarray[i] = = 0) {k++;}} int newarray[] = new int[(oldarray.length-k)];int j = 0;for (int i = 0; i < oldarray.length; i++) {if (oldarray[i]! = 0) {Newarray[j] = oldarray[i];j++;}} System.out.println (); System.out.println ("------------print NewArray--------------"), for (int i:newarray) {System.out.print (i + "");} System.out.println (); System.out.println ("newarray.length =" + newarray.length); System.out.println ("k =" + k);}}
Operation Result:
------------Print Oldarray--------------1 3 4 5 0 0 0 8 4 5 0 9 1------------print NewArray--------------1 3 4 5 8 4 5 9 1 newarray.length = 9k = 4
Given an array, remove the 0 elements and assign the remaining elements to the new array