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)
我唯一需要知道的是,为什么提示(“请在一行中最多输入十个数字:”)会打印两次
2条答案
按热度按时间xxe27gdn1#
你在打电话吗
getUserInput()
以及calculateAvg()
方法在这里。相反,只需使用传入的参数变量。当然,要获得您想要的行为,您可能需要在其他方法中稍微改变一下:
以及:
cxfofazt2#
你在打电话给警察
getUserInput()
方法两次:每次一次printResults()
方法和一次性calculateAvg()
.您可能需要进行以下更改:
到