如何使用某种逻辑将数组复制到另一个数组

时间:2016-06-30 07:00:27

标签: java arrays sorting

我需要编写将一个数组复制到另一个数组的代码。按顺序复制所有元素

  1. 大于0,
  2. 然后连续所有元素等于0,
  3. 然后连续所有元素都小于0.
  4. 这是我尝试执行此任务失败的原因:

    public static void main(String[] args)
    {
        int[] arr = new int[100];
        Random random = new Random();
    
        for (int i = 0; i < arr.length; i++)
        {
            int randNum = random.nextInt(600) - 350;
            arr[i] = randNum;
        }
        int[] newArr = new int[100];
        for (int i = 0; i < arr.length; i++)
        {
            if (arr[i] > 0)
            {
                System.arraycopy(arr, arr[i], newArr, 0, 100);
    
                // arraycopy() Not works!
                // I tryed to compare each element in array greater than 0 
                // and copy it to newArr
    
            }
        }
        System.out.println(Arrays.toString(newArr));
    

    为什么System.arraycopy无效?

2 个答案:

答案 0 :(得分:1)

看,你是每个单元格复制数组!所以内循环看起来像:

public static void main(String[] args)
{
    int[] arr = new int[100], newArr = new int[100];
    int j=0;
    Random random = new Random();

    for (int i = 0; i < arr.length; i++)
    {
        int randNum = random.nextInt(600) - 350;
        arr[i] = randNum;
    }

    for (int i = 0; i < arr.length; i++)
    {
        if (arr[i] > 0){
            newArr[j]=arr[i];
            j++;
        }
    }

    // and add code for numbers=0 and less than 0. So you should append code:
    for (int i = 0; i < arr.length; i++)
    {
        if (arr[i] == 0){
            newArr[j]=arr[i];
            j++;
        }
    }

    for (int i = 0; i < arr.length; i++)
    {
        if (arr[i] < 0){
            newArr[j]=arr[i];
            j++;
        }
    }

    System.out.println(Arrays.toString(newArr));
}

答案 1 :(得分:0)

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'