具有任意数量输入的Java平均程序
我要做的是一个平均程序,它接受任意数量的输入。到目前为止,我需要让用户指定他们想要平均多少个数字,如果他们没有给出那么多数字,程序就会崩溃。我有没有办法让他们放尽可能多的数字,然后设置数组长度 以下是我现在使用的代码:具有任意数量输入的Java平均程序,java,average,Java,Average,我要做的是一个平均程序,它接受任意数量的输入。到目前为止,我需要让用户指定他们想要平均多少个数字,如果他们没有给出那么多数字,程序就会崩溃。我有没有办法让他们放尽可能多的数字,然后设置数组长度 以下是我现在使用的代码: import java.util.*; public class Average_any { public static void main (String[] args) { Scanner scan = new Scanner (System.in)
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);
}
}
import java.util.*;
公共课平均分
{
公共静态void main(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
System.out.println(“要输入多少个数字?”);
final int ARRAY_LENGTH=scan.nextInt();
System.out.println(“请键入您要查找的平均值,”
+“然后键入\“完成\”);
System.out.println(“警告:仅键入您指定的确切数字量。”);
//若用户未输入相同的数字,则会导致崩溃
double[]number=新的double[ARRAY_LENGTH];
做{
for(int i=0;i
(以防万一有人想知道,不,这不是学校作业,我只是想知道,因为我们在学校做了一个更简单的版本)把数组从等式中完全去掉
Scanner scan=新的扫描仪(System.in);
双倍合计=0;
整数计数=0;
while(scan.hasNextDouble()){
总计+=扫描.nextDouble();
计数++;
}
双倍平均数=总数/计数;
你听说过列表吗
?不,对不起,除了HTML和CSS之外,我对编码有点陌生(这是一个略带修辞的问题。我真的建议你对列表进行一些研究。)看看java.util.List
,java.util.ArrayList
和java.util.LinkedList
。您几乎应该始终使用它们,而不是本机数组。你会发现很多关于如何使用它们的教程。它们也是这里的解决方案。谢谢,这比使用数组或列表要快得多