Given an array, remove the 0 elements and assign the remaining elements to the new array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.