用java中的三种方法和for循环求平均值

xwbd5t1u  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(347)

Package 平均方法;
导入java.util.scanner;

public class AverageWithMethods {

    public static void main(String[] args) {
        String userInput = "";
        double avgVal = 0;
        //calculateAvg(userInput);
        //getUserInput();
        printResults(userInput, avgVal);
    }

    public static String getUserInput() {
        String userInput;
        Scanner scnr = new Scanner(System.in);
        System.out.print("Please enter up to ten numbers in one line: ");
        userInput = scnr.nextLine();
        return userInput;
    }

    public static double calculateAvg(String userInput) {
        double avgVal = 0;
        double totSum = 0;
        int i;
        String newUserInput[] = getUserInput().split(" ");
        double[] userInputArray = new double[newUserInput.length];

        for (i = 0; i < newUserInput.length; ++i) {
            String userInputString = newUserInput[i];
            userInputArray[i] = Double.parseDouble(userInputString);
            totSum +=userInputArray[i];
            avgVal = totSum/newUserInput.length;
        }
        return avgVal;
    }

    public static void printResults(String userInput, double avgVal) {
        System.out.println("The average of the numbers " + getUserInput() + " is " + calculateAvg(userInput));
    }
}

这是我的输出。

Please enter up to ten numbers in one line: 10 20 30
Please enter up to ten numbers in one line: 10 20 30
The average of the numbers 10 20 30 is 20.0
BUILD SUCCESSFUL (total time: 6 seconds)

我唯一需要知道的是,为什么提示(“请在一行中最多输入十个数字:”)会打印两次

xxe27gdn

xxe27gdn1#

public static void printResults(String userInput, double avgVal) {
    System.out.println("The average of the numbers " + getUserInput() + " is " + calculateAvg(userInput));
}

你在打电话吗 getUserInput() 以及 calculateAvg() 方法在这里。相反,只需使用传入的参数变量。

public static void printResults(String userInput, double avgVal) {
    System.out.println("The average of the numbers " + userInput + " is " + avgVal);
}

当然,要获得您想要的行为,您可能需要在其他方法中稍微改变一下:

public static void main(String[] args) {
    String userInput = getUserInput();
    double avgVal = calculateAvg(userInput);

    printResults(userInput, avgVal);
}

以及:

String newUserInput[] = userInput.split(" ");
cxfofazt

cxfofazt2#

你在打电话给警察 getUserInput() 方法两次:每次一次 printResults() 方法和一次性 calculateAvg() .
您可能需要进行以下更改:

String newUserInput[] = getUserInput().split(" ");

String newUserInput[] = userInput.split(" ");

相关问题