【问题标题】:Copy specific numbers from one array to another将特定数字从一个数组复制到另一个数组
【发布时间】:2021-11-17 09:53:11
【问题描述】:

有没有办法将特定数字从一个数组复制到另一个数组?
例如:
我有一个数组{1, 2, 3, 4, 5}
我想将奇数和偶数复制到单独的数组中。所以,结果应该是
{2, 4}, {1, 3, 5}

【问题讨论】:

  • 是的,有办法。但我敢肯定这不是你的实际问题。您对该作业的哪一部分有疑问?迭代现有数组?判断一个数是奇数还是偶数?将这些数字排序到一个新数组中?

标签: java arrays copy


【解决方案1】:

试试这个。

public static void main(String[] args) {
    int[] array = {1, 2, 3, 4, 5};

    int[] even = IntStream.of(array).filter(i -> i % 2 == 0).toArray();
    int[] odd = IntStream.of(array).filter(i -> i % 2 != 0).toArray();

    System.out.println("even = " + Arrays.toString(even));
    System.out.println("odd = " + Arrays.toString(odd));
}

输出:

even = [2, 4]
odd = [1, 3, 5]

【讨论】:

    【解决方案2】:
    int[] ls={1, 2, 3, 4, 5};
    
    List<Integer> odd=new ArrayList<Integer>();
    for (int l :ls) {
        if(l%2==1) {
            odd.add(l);
        }
    }
    System.out.println(odd);
    
    List<Integer> even=new ArrayList<Integer>();
    for (int l :ls) {
        if(l%2==0) {
            even.add(l);
        }
    }
    System.out.println(even);
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案3】:

    试试这个

    import java.util.*;
    
    class Dragon {
        public static void main(String[] args) {
            int[] list = { 1, 2, 3, 4, 5 };
    
            List<Integer> oddList = new ArrayList<Integer>();
            List<Integer> evenList = new ArrayList<Integer>();
    
            for (int l : list) {
                if (l % 2 == 0)
                    evenList.add(l);
                else
                    oddList.add(l);
            }
            System.out.println("Odd = " + oddList);
            System.out.println("Even = " + evenList);
        }
    }
    

    输出

    Odd = [1, 3, 5]
    Even = [2, 4]
    

    【讨论】:

      猜你喜欢
      • 2015-06-17
      • 2016-04-10
      • 2022-07-05
      • 1970-01-01
      • 2018-02-17
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      相关资源
      最近更新 更多