我需要计算数组中整数的随机输入。一切工作正常,但我为每个Input获得了数组内所有值的新计算。
有人知道如何解决这个问题吗?
这是我的代码:
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
while (sc.hasNextInt()) { // this loop breaks there is no more int input.
numbers.add(sc.nextInt());
int l = numbers.size();
double total = 0;
for (int i = 0; i < numbers.size(); i++) {
total = total + numbers.get(i);
double average = total / numbers.size();
System.out.println("The average is: " + average);
}
System.out.println(numbers);
}
}
答案 0 :(得分:2)
正如所指出的,您应该仅在找到所有数字的总和后 来计算数字的平均值。
您的程序需要分成几个单独的步骤,这些步骤应该一个接一个地执行,而不是一次执行:
检索用户输入,将每个整数添加到列表中
遍历列表中的所有整数,并添加到total
计算平均值
显示结果
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
while (sc.hasNextInt())
numbers.add(sc.nextInt());
sc.close(); // Remember to close the input stream when finished
double total = 0;
for (int num : numbers) // Loop through all ints in the list
total += num; // Add each int to total
double average = total / numbers.size();
System.out.println("The average is: " + average);
System.out.println(numbers);
}
答案 1 :(得分:-2)
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt()) { // this loop breaks there is no more int input.
numbers.add(sc.nextInt());
int l = numbers.size();
double total = 0;
}
for (int i = 0; i < numbers.size(); i++) {
total = total + numbers.get(i);
double average = total / numbers.size();
System.out.println("The average is: " + average);
}
System.out.println(numbers);
}
答案 2 :(得分:-2)
这应该可以解决您的问题。 每个循环的Java文档: https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html
public static void main(String[] args) throws IOException {
double total;
double average;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt()) { // this loop breaks there is no more int input.
numbers.add(sc.nextInt());
int l = numbers.size(); //this line is redundant as its never used
//this is a different and more efficient way to traverse through the list for this //problem, check comment for the documentation
for (int currentNumberInList : numbers) {
total = total + currentNumberInList;
}
System.out.println(numbers); //this only prints the numbers you
//stored in the list
average = total / numbers.size();
System.out.println("The average is: " + average);
}
}