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));
}
}
这是我的输出。
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)
我唯一需要知道的是为什么提示符(&#34;请在一行中最多输入10个数字:&#34;)打印两次
答案 0 :(得分:2)
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(" ");
和
my_hash.select{|k, v| my_selected_keys.include?(k) }.values.min_by(&:last)
答案 1 :(得分:1)
您正在调用getUserInput()
方法两次:一次使用printResults()
方法,一次使用calculateAvg()
。
您可能希望进行以下更改:
String newUserInput[] = getUserInput().split(" ");
到
String newUserInput[] = userInput.split(" ");