复制没有指定元素的数组java [英] copy array without specified element java

查看:35
本文介绍了复制没有指定元素的数组java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试复制一个没有指定元素的数组.假设我有以下数组:

i'm trying copy an array without a specified element. Let's say I have the following arrays:

int[] array = {1,2,3,4,5,6,7,8,9};
int[] array2 = new int[array.length-1];

我想要的是将数组复制到 array2 而不包含包含 int "6" 的元素,因此它将包含"{1,2,3,4,5,7,8,9}"

what I want is to copy array to array2 without the element containing the int "6" so it will contain "{1,2,3,4,5,7,8,9}"

我只想使用 for 循环,这是我目前所拥有的,但它不起作用

I only want to use for loops and this is what I have so far but it doesnt work

int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int[] array2= new int[array.length - 1];
    int remove = 6;
    for (int i = 0; i < array2.length; i++) {
        if (array[i] != remove) {
            array2[i] = array[i];
        } else {
            array2[i] = array[i + 1];
            i++;
        }
    }
    for (int i = 0; i < array2.length; i++) {
        System.out.println(array2[i]);
    }

谢谢

推荐答案

int j = 0;
int count = 0; //Set this variable to the number of times the 'remove' item appears in the list
int[] array2 = new int[array.length - count];
int remove = 6;
for(int i=0; i < array.length; i++)
{
   if(array[i] != remove)
       array2[j++] = array[i];
}

这篇关于复制没有指定元素的数组java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆