41.4k views
5 votes
This lab was designed to teach you more about using Scanner to chop up Strings. Lab Description : Take a group of numbers all on the same line and average the numbers. First, total up all of the numbers. Then, take the total and divide that by the number of numbers. Format the average to three decimal places Sample Data : 9 10 5 20 11 22 33 44 55 66 77 4B 52 29 10D 50 29 D 100 90 95 98 100 97 Files Needed :: Average.java AverageRunner.java Sample Output: 9 10 5 20 average = 11.000 11 22 33 44 55 66 77 average = 44.000 48 52 29 100 50 29 average - 51.333 0 average - 0.000 100 90 95 98 100 97 average - 96.667

1 Answer

4 votes

Answer:

The program is as follows:

import java.util.*;

public class Main{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String score;

System.out.print("Scores: ");

score = input.nextLine();

String[] scores_string = score.split(" ");

double total = 0;

for(int i = 0; i<scores_string.length;i++){

total+= Double.parseDouble(scores_string[i]); }

double average = total/scores_string.length;

System.out.format("Average: %.3f", average); }

}

Step-by-step explanation:

This declares score as string

String score;

This prompts the user for scores

System.out.print("Scores: ");

This gets the input from the user

score = input.nextLine();

This splits the scores into an array

String[] scores_string = score.split(" ");

This initializes total to 0

double total = 0;

This iterates through the scores

for(int i = 0; i<scores_string.length;i++){

This calculates the sum by first converting each entry to double

total+= Double.parseDouble(scores_string[i]); }

The average is calculated here

double average = total/scores_string.length;

This prints the average

System.out.format("Average: %.3f", average); }

}

User Enya
by
6.0k points