Finding average using three methods and a for loop

2019-09-17 10:52发布

package averagewithmethods;

import 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));
    }
}

This is my output.

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)

The only thing I need to know is why does the prompt ("Please enter up to ten numbers in one line: ") print twice

2条回答
混吃等死
2楼-- · 2019-09-17 11:44
public static void printResults(String userInput, double avgVal) {
    System.out.println("The average of the numbers " + getUserInput() + " is " + calculateAvg(userInput));
}

You're calling getUserInput() and calculateAvg() methods again here. Instead, just use the parameter variables you passed in.

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

Of course, to get the behavior you're looking for, you'll probably want to change things around a little in your other methods:

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

    printResults(userInput, avgVal);
}

And:

String newUserInput[] = userInput.split(" ");
查看更多
爷的心禁止访问
3楼-- · 2019-09-17 11:54

You're calling the getUserInput() method twice: once in the printResults() method and once in the calculateAvg().

You probably want to make the following change:

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

to

String newUserInput[] = userInput.split(" ");
查看更多
登录 后发表回答