zoukankan      html  css  js  c++  java
  • 给定数组,去掉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
    

      

  • 相关阅读:
    spring boot 整合elasticsearch
    elasticsearch 高级查询
    elasticsearch 基本操作
    day9--回顾
    day9--多线程与多进程
    day9--paramiko模块
    day10--异步IO数据库队列缓存
    数据库连接池
    数据库事务的四大特性以及事务的隔离级别
    使用JDBC进行数据库的事务操作(2)
  • 原文地址:https://www.cnblogs.com/Andya/p/5692848.html
Copyright © 2011-2022 走看看