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
You're calling
getUserInput()
andcalculateAvg()
methods again here. Instead, just use the parameter variables you passed in.Of course, to get the behavior you're looking for, you'll probably want to change things around a little in your other methods:
And:
You're calling the
getUserInput()
method twice: once in theprintResults()
method and once in thecalculateAvg()
.You probably want to make the following change:
to