'Calculate an Average from user input of five to ten numbers using Methods

My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.

It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?

public class AverageWithMethods {

    public static void main(String[] args) {
        String userNumbers = getUserNums();
        double average = userNumAvg(userNumbers);
        printAverage(0, userNumbers);

    }

    public static String getUserNums() {
        Scanner in = new Scanner(System.in);
        String userNumInput = "";
        System.out.print("Please enter five to ten numbers separated by spaces: ");
        userNumInput = in.nextLine();
        return userNumInput;
    }

    public static double userNumAvg(String userNumInput) {
        Scanner in = new Scanner(System.in);
        Scanner line = new Scanner(in.nextLine());
        
        double count = 0;
        double average = 0.0;
        double sum =0;
        

        while (in.hasNextDouble()) {
            count++;
            sum = line.nextDouble();

        }
        if (count != 0) {
            average = sum / count;
            count = Double.parseDouble(userNumInput); 
        }
        
        return average;
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);

    }
}


Solution 1:[1]

From your first section of code I am making the assumption all the numbers are entered on a single line all at once.

My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers?

The Scanner object you are using has a method hasNextInt() so you can construct a simple while loop to figure out how many numbers there are.

Scanner line = new Scanner(in.nextLine()); // Feed line into scanner
int numbers = 0;
double total = 0.0;
while(in.hasNextInt()) { // read all the numbers
    numbers++;
    total += line.nextDouble();
}
line.close(); // Good habit

You can then compute your average with all this information:

double avg = total/numbers;

Notes:

  • Making total a double to avoid integer math when computing the average. There are obviously other ways to avoid integer math and I can include more if you would like.

  • I use a second Scanner with a String parameter of in.nextLine() because if you skip that step, the code won't terminate when reading a continuous input stream such as a console/terminal. This is because there will be a next int possible since the terminal is still accepting input.

Solution 2:[2]

count how many spaces there are in your string. You can do this either by looping and checking the char value or you can do a replace on the string and compare the size of the new String

e.g.

    String fiveNums = "1 2 3 4 5";
    String noSpaces = fiveNums.replace(" ", "");
    System.out.println(fiveNums.length() - noSpaces.length());

Solution 3:[3]

When you want to understand how many numbers input the user, you can:

String[] userNumInput = in.nextLine().split(" ");
int quantity = userNumInput.length;

User input quantity numbers.

Here is one of the possible ways to do from your original code:

import java.util.Scanner;

public class GetAverage {

    public GetAverage() {
        String getStr = getUserNums();
        double result = userAvg(getStr);
        printAverage(result, getStr);

    }

    public String getUserNums() {
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter five to ten numbers separated by spaces: ");
        return in.nextLine();
    }

    public static double userAvg(String str) {
        String[] arr = str.split(" ");
        double sum = 0.0;
        double average = 0.0;
        for (int i = 0; i < arr.length; i++) {
            sum += Integer.parseInt(arr[i]);
        }
        if (arr.length > 0) {
            average = sum / arr.length;
        }

        return average; // how do I get the program to count what to divide by since user can input 5- 10?
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + "is %.2f", average);

    }

    public static void main(String[] args) {
        new GetAverage();

    }
}

OUTPUT:

Please enter five to ten numbers separated by spaces: 
5 7 8 9 6 3 2 4
The average of the numbers 5 7 8 9 6 3 2 4is 5.50

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Scary Wombat
Solution 3