import java.io.*;
import java.util.*;
class Mean {
int n, a[] = new int[n] , sum = 0, avg;
public int getMean() {
Scanner in = new Scanner(System.in);
n = in.nextInt();
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
sum = sum + a[i];
}
avg = sum / n;
return avg;
}
public void displayMean() {
System.out.println(avg);
}
}
public class TestClass {
public static void main(String[] args) {
Mean obj = new Mean();
obj.getMean();
obj.displayMean();
}
}
测试用例1: 5
1 3 4 5 6
预期输出: 3
答案 0 :(得分:1)
读取a
的值后,必须分配数组n
。在您的代码中,n
被初始化为0
,数组a
的长度为零。即使稍后更改n
的值,a
的长度也不会改变。
定义行变为:
int n, a[] , sum = 0, avg;
您可以这样分配:
n = in.nextInt();
a = new int[n];