该程序要求用户输入填充数组列表的数字。如果用户输入0,则程序将所有先前输入的数字相加并对它们求平均值。它不适合我,所以我怎么能让这个工作?
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Calculation {
static Toolkit tools = new Toolkit();
public static void main(String [] args) {
double average = 0.0;
double sum = 0;
int i =0;
int num = 0;
int nElements = 0;
Scanner console = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.println("Enter value: ");
num = console.nextInt();
while(num != 0) {
value.add(new Integer(num));
}
for(i = 0; i < value.size(); i++) {
sum += value.size();
}
average = sum / value.size();
System.out.println("Number of values read: " + value.size());
System.out.println("Values sum: " + sum + "Values average: " + average);
System.exit(0);
}
}
答案 0 :(得分:1)
你需要阅读循环内部,你有:
public static void main(String [] args) {
double average = 0.0;
double sum = 0;
int i =0;
int num = 0;
int nElements = 0;
Scanner console = new Scanner(System.in);
ArrayList<Integer> value = new ArrayList<Integer>();
System.out.println("Enter value: ");
num = console.nextInt();
while(num != 0) {
value.add(new Integer(num));
num = console.nextInt();
}
for(i = 0; i < value.size(); i++) {
sum += value.get(i);
}
average = sum / value.size();
System.out.println("Number of values read: " + value.size());
System.out.println("Values sum: " + sum + " Values average: " + average);
System.exit(0);
}