简体   繁体   中英

Sum of elements of an array java

Write a method called sumArray that takes an array of integers as a parameter, and returns an integer equal to the sum of all elements in the array. I keep getting zero for my output.

public static int sumArray( int[] sum) {
    int add=0;
    for(int i=0; i< sum.length; i++) { 
       sum[i]+= add;
    }

    return add;
}

您以错误的方式添加了附件,应该是:

add += sum[i]
public static int sumArray( int[] sum) {
    int add=0;
    for (int i=0; i< sum.length; i++) {
        add+=sum[i];
    }
    return add;
}

Your variable on the left is being added with each element of sum.

You are trying to add add variable that equals zero to each element of sum array, and then return add variable that still equals zero. If you swap the places of variable add and array element sum[i] , you will begin to add sum[i] 's value into add at each iteration.

Please make a search before you ask such a trivial question.

我知道的最短方法是:

int add=Arrays.stream(sum).sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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