具有任意数量输入的Java平均程序

时间:2017-09-17 19:35:47

标签: java average

我想要做的是一个平均程序,可以接受任意数量的输入。到目前为止,我需要让用户指定他们想要平均的数量,如果他们没有给出那么多数字,程序就会崩溃。有什么方法可以让他们把它们放到他们想要的数量之后,然后设置数组长度?

以下是我现在使用的代码:

import java.util.*;

public class Average_any
{
    public static void main (String[] args) {
        Scanner scan = new Scanner (System.in);

        System.out.println ("How many numbers do you want to enter?");

        final int ARRAY_LENGTH = scan.nextInt();

        System.out.println ("Please type the numbers you want to find the average of, "
                            + "and then type \"Done\".");
        System.out.println ("Warning: Only type the exact amount of numbers that you specified.");
        // If user doesn't enter same number, results in crash
        double[] numbers = new double [ARRAY_LENGTH];
        do {
            for (int i = 0; i < numbers.length; i++) {
                while (!scan.hasNextInt()) {
                System.out.println("That's not a number!");
                scan.next(); //Need this to enter another input
                }
                numbers[i] = scan.nextInt();
            }
        } while (!scan.hasNext("Done"));

        double total = 0;
        for (int i = 0; i < numbers.length; i++) {
            total += numbers[i];
        }

        double average = total/ARRAY_LENGTH;

        System.out.println ("Your average is: " + average);
    }
}

(万一有人想知道,这不是学校作业,我只是想知道因为我们在学校做了一个更简单的版本)

1 个答案:

答案 0 :(得分:1)

将数组完全取出等式

Scanner scan = new Scanner (System.in);
double total = 0;
int count = 0;

while (scan.hasNextDouble()) {
    total += scan.nextDouble();
    count ++;
}
double average = total / count;