Adding a variables in the array into another array

Sangcheol Yu :

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}. 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:

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. 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. Also, the changes that I've made in the for statement doesn't last, so this is a problem as well. How can I fix this situation? Please help!

Thanga :

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

  }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=374424&siteId=1