且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用用户输入获取平均值(JAVA)

更新时间:2023-11-14 14:23:34

问题是你从来没有读过输入.实现扫描器和读取用户输入的正确方法如下:

The problem is that you are never reading the input. The proper way to implement a scanner and read user input is as follows:

Scanner sc = new Scanner(System.in);

double userInput = 0;

System.out.print("Please enter a number");

userInput = sc.nextDouble();    // This is what you are missing

因此,您可以将变量 userInput 添加到 ArrayList 中,或者直接读入 ArrayList.

So then you can either add the variable userInput into the ArrayList, or alternatively directly read into the ArrayList.

更新:

这是您想要的代码.它将询问用户输入的数量,然后将每个输入添加到数组中.

This is the code you want. It will ask the user for the number of inputs, then it will add each input into the array.

public static double[] getUserInput() {

    Scanner sc = new Scanner(System.in);

    List<Double> inputList = new ArrayList<Double>();

    System.out.println("Please enter how many numbers you will be inputing");
    int numberOfInputs = sc.nextInt();

    for (int i = 0; i < numberOfInputs; i++) {
        System.out.println("Please enter a number");
        double userInput = sc.nextDouble(); // Store user inputed double into temporary variable
        inputList.add(userInput); // Add temporary variable into ArrayList
    }
    sc.close();

    double[] arr = new double[inputList.size()];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = inputList.get(i);
    }
    return arr;
}