# Java 程序总结数组的元素

> 原文： [https://beginnersbook.com/2014/01/java-program-to-sum-the-elements-of-an-array/](https://beginnersbook.com/2014/01/java-program-to-sum-the-elements-of-an-array/)

在本教程中，我们将看到**如何总结数组**的所有元素。

计划 1：没有用户互动

```java
/**
 * @author: BeginnersBook.com
 * @description: Get sum of array elements
 */
class SumOfArray{
   public static void main(String args[]){
      int[] array = {10, 20, 30, 40, 50, 10};
      int sum = 0;
      //Advanced for loop
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}
```

输出：

```java
Sum of array elements is:160
```

程序 2：用户输入数组的元素

```java
/**
 * @author: BeginnersBook.com
 * @description: User would enter the 10 elements
 * and the program will store them into an array and 
 * will display the sum of them.
 */
import java.util.Scanner;
class SumDemo{
   public static void main(String args[]){
      Scanner scanner = new Scanner(System.in);
      int[] array = new int[10];
      int sum = 0;
      System.out.println("Enter the elements:");
      for (int i=0; i<10; i++)
      {
    	  array[i] = scanner.nextInt();
      }
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}
```

Output:

```java
Enter the elements:
1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55
```