在本教程中,我们将看到如何汇总数组的所有元素。
计划 1:没有用户互动
/** * @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); }}输出:
Sum of array elements is:160
程序 2:用户输入数组的元素
/** * @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); }}
输出:
Enter the elements:12345678910Sum of array elements is:55
