Java语言怎么实现自动清除一个数组中所有为0的数字,合并剩下的数字得到一个新的数组呢

Java语言怎么实现自动清除一个数组中所有为0的数字,合并剩下的数字得到一个新的数组呢

int [] listSrc = new int[]{1,2,3,0,1,2,3,4,6,0,1};
List<Integer> listTag = new ArrayList<>();
for(int value : listSrc)
{
    if(value == 0)
      conitnue;
   listTag.add(value);
}

// 如果没有一定要转回数组,则直接使用listTag则可,否则可以按以下代码转回数组
// 用listTag.toArray函数只能转换成Integer[],要转换成int[]只能自己写转换

int[] listOut = new int[listTag.size()];
for(int i = 0; i < listOut.length; i ++)
      listOut[i] = listTag.get(i);

【以下回答由 GPT 生成】

要实现这个功能,可以按照以下步骤操作:

  1. 创建一个空的ArrayList来存储非零数字。
ArrayList<Integer> result = new ArrayList<>();
  1. 遍历原始数组,将非零数字添加到ArrayList中。
for (int i = 0; i < array.length; i++) {
    if (array[i] != 0) {
        result.add(array[i]);
    }
}
  1. 将ArrayList转换为新的数组。
int[] newArray = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
    newArray[i] = result.get(i);
}
  1. 完整的代码示例:
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 0, 3, 0, 5, 0, 7};

        ArrayList<Integer> result = new ArrayList<>();

        for (int i = 0; i < array.length; i++) {
            if (array[i] != 0) {
                result.add(array[i]);
            }
        }

        int[] newArray = new int[result.size()];

        for (int i = 0; i < result.size(); i++) {
            newArray[i] = result.get(i);
            System.out.print(newArray[i] + " ");
        }
    }
}

以上代码将输出:1 3 5 7,即清除了数组中所有为0的数字,并将剩余数字合并为一个新的数组。

希望对你有所帮助!



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^