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

编程实现给定数组,将数组中值为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 = 9
k = 4

  

转载于:https://www.cnblogs.com/Andya/p/5692848.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值