数字串的平均值

时间:2018-03-19 01:40:10

标签: java methods

我正在尝试编写一个程序,该程序从用户那里获取5-10个数字的列表并计算它们的平均值。我已经完成了大部分工作;但是,我在'numAvg'方法上遇到了麻烦。我需要的输出是“数字插入数字的平均值 平均值。”我正确地显示数字;但是,无论我输入什么数字,平均值始终为0.0。我想知道是否有人能指出我正确的方向来正确显示平均值?

package averagewithmethods;

import java.util.Scanner;

public class AverageWithMethods {

public static void main(String[] args) {

    String userInput = getNumbers();
    numAvg(userInput);
    printAverage(0, userInput);
}

public static String getNumbers() {

    Scanner scnr = new Scanner(System.in);
    String userInput = "";

    System.out.println("Please enter 5-10 numbers seperated by spaces: ");
    userInput = scnr.nextLine();

    return userInput;
}

public static double numAvg(String userInput) {

    Scanner in = new Scanner(System.in);
    Scanner line = new Scanner(userInput);

    int numbers = 0;
    double total = 0.0;

    while (line.hasNextDouble()) {

        numbers++;
        total += line.nextDouble();

    }
    line.close();

    double average = total/numbers;

    return average;
}

public static void printAverage(double average, String userInput) {

    System.out.println("The average of the numbers " + userInput + " is " + average);
}
}

1 个答案:

答案 0 :(得分:1)

问题在于您拨打printAverage的方式。

numAvg(userInput);
printAverage(0, userInput);

你有硬编码0。而是传递numAvg的结果。像,

double avg = numAvg(userInput);
printAverage(avg, userInput); // the average. not 0.