423,897 views
36 votes
36 votes
The program prompts the user for five to ten numbers all on one line, separated by spaces, calculates the average of those numbers, and displays the numbers and their average to the user.

The program uses methods to:

1) get the numbers entered by the user all on one line separated by spaces;

2) calculate the average of the numbers entered by the user; and

3) print the results.

The first method should take no arguments and return a String of numbers separated by spaces.

The second method should take a String as its only argument and return a double (the average).

The third method should take a String and a double as arguments but have no return value.

IF user input is: 20 40 60 80 100

User Vegar
by
2.9k points

1 Answer

18 votes
18 votes

Answer:

import java.util.Scanner;

public class AverageDemo

{

public static String getNumbers()

{

String numbers;

Scanner scn = new Scanner(System.in);

System.out.println("Enter five to ten numbers all on one line, separated by spaces: ");

numbers = scn.nextLine();

return numbers;

}

public static double calcAverage(String numbers)

{

String[] values = numbers.split(" ");

double total = 0;

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

{

total += Integer.parseInt(values[i]);

}

if (values.length == 0)

return 0.0;

else

return (total / values.length);

}

// Method definition of printResults: print the results

public static void printResults(String numbers, double average)

{

System.out.printf("\\The average of the numbers %s is %.2f\\", numbers, average);

}

// main method

public static void main(String[] args)

{

// Call the methods

String numbers = getNumbers();

double average = calcAverage(numbers);

printResults(numbers, average);

}

}

Output:

The program prompts the user for five to ten numbers all on one line, separated by-example-1
User Jolean
by
2.5k points