Java 数组来计算平均值

Java 数组来计算平均值,java,Java,我正在尝试使用数组计算平均条目数。该方法无法正确执行。感谢您的帮助 public static double calculateAverage (double[] Array) { int person= 0; int total= 0; for(int i = 0; i < person.length; i++) { total += avgCustomer[i]; } double avgPerson = total/ person.leng

我正在尝试使用数组计算平均条目数。该方法无法正确执行。感谢您的帮助

public static double calculateAverage (double[] Array) {
    int person= 0;
    int total= 0;


    for(int i = 0; i < person.length; i++)
{
    total += avgCustomer[i];
}
    double avgPerson = total/ person.length;
    return avgPerson;
公共静态双计算范围(双[]数组){
int person=0;
int-total=0;
for(int i=0;i
您有一个数组越界异常。请确保以i=0而不是i=1启动ur for循环

    for (i = 0; i <= customer; i++) {
    ......}

对于(i=0;i问题的至少一部分是:

int customer = 0;
...
double[] bfpArray = new double[customer];
int[] avgCustomer = new int[customer];

System.out.print("Please enter the number of customers: ");
customer = input.nextInt();
因为当前代码将创建长度为0的数组
bfpArray
avgCustomer

将阵列初始化移动到收集客户数之后(尽管最好确保条目有效),这将有助于:

System.out.print("Please enter the number of customers: ");
customer = input.nextInt();

double[] bfpArray = new double[customer];
int[] avgCustomer = new int[customer];
然后,正如@shikai ng所指出的,您需要调整您的循环:

for (i = 0; i < customer; i++) {
for(i=0;i

由于Java数组是基于0的。

您所说的“隐藏”和“可见”是什么意思?您所说的“崩溃”是什么意思?所以您的问题是“为什么在删除变量声明时会出现编译器错误?”我猜
bfpArray
avgCustomer
没有做预期的事情,因为它们被初始化为
0
@smokey,仔细查看
calculateAverage
的代码。它在初始化方面是否也有同样的缺陷?