简体   繁体   中英

(JAVA) Addition of integers in an Array

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

}

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

You can also use for each to find the sum. Find the code below

public static int sumArray(int[] arr){
    int sum = 0;
    for(int i:arr) {
        sum+=i;
    }
    return sum;   
}

Return statement should be outside of for loop. When the return statement is in the loop sumArray method returns the value of the first element of inputArray. Below I also added for each loop and replaced name arr with parameter name inputArray.

public static int sumArray(int[] inputArray){
int sum = 0;
for (int element : inputArray){
    sum += inputArray[i];
}
return sum;
}

In java-8 you can use streams like this:

public static int sumArray(int[] arr) {
    int sum = IntStream.of(arr).sum();
    return sum;
}

Output: The sum is: 15.

It's in the package java.util.stream

I think this should solve your problem:

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

public static int sumArray(int[] inputArray){
   int sum = 0;
   for (int i = 0; i < inputArray.length; i++){
       sum += inputArray[i];
       return 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