使用用户输入获取平均值(JAVA) [英] Use user input to get mean (JAVA)

查看:53
本文介绍了使用用户输入获取平均值(JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取用户输入,并使用他们的输入来计算平均值.我遇到的问题是我的代码没有提示用户输入用于计算平均值的整数.

I am trying to get user input, and use their input to calculate the mean. The problem I am having is that my code does not prompt the user for a integer to use to calculate the mean.

这只是代码片段.

public static double[] getUserInput() {

    Scanner sc = new Scanner(System.in);

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

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


    System.out.println(inputList);
    double arr[] = new double[inputList.size()];
    System.out.println(inputList.size());
    return arr;
}

public static double arithmeticMean(double[] nums) {

    double mean = 0;
    double sum = 0;

    // gets the mean
    try {
        for (int i = 0; i < nums.length; i++) {
            sum = sum + nums[i];
        }
        mean = sum / nums.length;
    } catch (ArithmeticException ex) {
        System.out.println(ex);
    }

    return mean;
}

推荐答案

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

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

这篇关于使用用户输入获取平均值(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆