给定数组,去掉0元素后将剩下的元素赋给新的数组

来源:互联网 发布:南京尹氏鸡汁汤包 知乎 编辑:程序博客网 时间:2024/05/03 14:27

编程实现给定数组,将数组中值为0的项去掉存入新的数组。

package com.liaojianya.chapter1;/** * This program demonstrates the way to remove zero from old array and insert into new array. * @author LIAO JIANYA * 2016年7月21日 */public class RemoveZero{public static void main(String[] args) {int k = 0;int oldArray[] = {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);}}

  运行结果:

------------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

  

0 0
原创粉丝点击