gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:14:48 25 4
gpt4 key购买 nike

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

这是我现在使用的代码:

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

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

最佳答案

将数组完全排除在等式之外

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

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

关于具有任意数量输入的 Java 平均程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46268124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com