简体   繁体   English

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

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

Today, I have a question about the list.今天,我有一个关于列表的问题。 I want to put the variables in the array into the another array.我想将数组中的变量放入另一个数组中。 For example, if there is a int[] list1 and int[] list2 = {1,2,3,4} and int[] list3 = {5,6,7}, I want to put the variables in list2 and list3 into the list1, making the list1 into {1,2 + 5, 3 + 6, 4 + 7}.例如,如果有一个int[] list1和int[] list2 = {1,2,3,4}和int[] list3 = {5,6,7},我想把变量放在list2和list3中进入 list1,使 list1 变成 {1,2 + 5, 3 + 6, 4 + 7}。 Below is the code that I have made:下面是我制作的代码:

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;
}

Next is the code of addVariable:接下来是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;
}

So, what I want to do is making the intlist whole, by using for statement and addVariable function.所以,我想要做的是通过使用 for 语句和 addVariable 函数使 intlist 完整。 But, the addVariable fuction is not complete, as the two lists can have different size, and the function that I've made didn't consider this.但是, addVariable 函数并不完整,因为两个列表可以有不同的大小,而我所做的函数没有考虑到这一点。 Also, the changes that I've made in the for statement doesn't last, so this is a problem as well.此外,我在 for 语句中所做的更改不会持续,所以这也是一个问题。 How can I fix this situation?我该如何解决这种情况? Please help!请帮忙!

This is the code you need这是你需要的代码

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