(JAVA) Addition of integers in an Array

utnicho :

I'm new to java programming so please excuse any misunderstandings or misinterpretations. I need to write a program with 2 methods, the first method declares an array of integers as shown and a variable that is the sum of this array then prints out the sum.

The second method is where my addition takes place. I've declared a variable "sum" equal to 0 so my addition can work, and a for loop that adds all integers based on the array length, returning the variable sum back to the main method. (From my current understanding of my program)

So far this does not work and I get 3 errors. One from my main method "cannot find symbol - inputArray" cannot find symbol in my for loop for "arr.length" and cannot find symbol in my " sum += arr[i]" Could someone please explain and possibly assist with why I am getting these errors. Thank you for your time.

public static void main(String[] args){
    int arr[] = {1,2,3,4,5};
    int sum = sumArray(inputArray);
    System.out.println("The sum is: "+sum);
}
public static int sumArray(int[] inputArray){
    int sum = 0;
    int i;
    for (i = 0; i < arr.length; i++){
        sum += arr[i];
        return sum;
    }   

}
Andronicus :

The variable name is inputArray. Also the return statement should be outside of the loop:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=341090&siteId=1