繁体   English   中英

将数组中的一个变量添加到另一个数组中

[英]Adding a variables in the array into another array

今天,我有一个关于列表的问题。 我想将数组中的变量放入另一个数组中。 例如,如果有一个int[] list1和int[] list2 = {1,2,3,4}和int[] list3 = {5,6,7},我想把变量放在list2和list3中进入 list1,使 list1 变成 {1,2 + 5, 3 + 6, 4 + 7}。 下面是我制作的代码:

public int function(int[] parameter) {
    int[] intlist;
    for (int i = 0; i < intlist.length; i++) {
        intlist = addVariable(int[] anotherlist); //the function addVariable(int[] parameter) gets a
        //int[] as a paremeter, makes a new int[](which has the same size as the parameter) at the 
        //inside of the function, add parameter's each and every varibles into the new int[] and 
        //returns the new int[]. and anotherlist keeps changing in the for statement. This is the 
        //function that I want to make.
    }
    return intlist;
}

接下来是addVariable的代码:

public static int[] addVariables(int[] intlist) {
        int[] intlist2 = new int[intlist.length];
        for(int i = 0; i < intlist.length; i++) {
            intlist2[i] += intlist[i];
        }
        return intlist2;
}

所以,我想要做的是通过使用 for 语句和 addVariable 函数使 intlist 完整。 但是, addVariable 函数并不完整,因为两个列表可以有不同的大小,而我所做的函数没有考虑到这一点。 此外,我在 for 语句中所做的更改不会持续,所以这也是一个问题。 我该如何解决这种情况? 请帮忙!

这是你需要的代码

public class Test {

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


    Test.addVariables(intlist, anotherlist);
    for (int i : intlist) {
        System.out.println(i);
    }

}

public static void addVariables(int[] intlist, int[] anotherlist) {

    for (int i = intlist.length - 1, j = anotherlist.length - 1; i >= 0 && j >= 0; i--, j--) {
        intlist[i] += anotherlist[j];
    }

  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM