4️⃣

#️⃣
Ch. 9 Arrays

# Average Score

Here is an application of an array in a program, which could be used by a teacher to calculate the average of 5 test scores.

``````// prompt user for 5 test scores
Scanner input = new Scanner(System.in);
System.out.print("Enter 5 test scores, separated by spaces: ");

// store the scores in an array
double[] scores = new double;
for (int i = 0; i < scores.length; i++) {
scores[i] = input.nextDouble();
}

input.close();

// calculate the sum of the scores
double sum = 0;
for (double score : scores) {
sum += score;
}

// calculate the average and display it
double average = sum / 5;
System.out.println("The average score is " + average);``````

Sample output:

``````Enter 5 test scores, separated by spaces: 45 99 89 97 23
The average score is 70.6
``````

# Multiple Inputs

Before, we only used Scanner for getting 1 value after a prompt. In this program, you’ll notice that in the highlighted portion of the code, `nextDouble()` is being called repeatedly. This allows us to read multiple `double` values, as long as they are separated by space. This kind of way to get user input can also be used for other Scanner methods such as `nextInt()`.

# Previous Section

3️⃣
9.3 Iterating through Arrays

5️⃣
9.5 Practice

⚖️