简体   繁体   English

计算平均值的数组

[英]Array to calculate an average

I'm attempting to calculate the average number of entries using an array.我正在尝试使用数组计算平均条目数。 The method doesn't execute properly.该方法没有正确执行。 Any help is appreciated.任何帮助表示赞赏。

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;

At least one part of the issue is this:问题的至少一部分是这样的:

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();

As this current code will create the arrays bfpArray and avgCustomer to have a length of 0.由于此当前代码将创建长度为 0 的数组bfpArrayavgCustomer

Moving the array initialization until after the number of customers has been collected (though it would be good to ensure that the entry is valid) would help:将数组初始化移动到收集到客户数量之后(尽管最好确保条目有效)会有所帮助:

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

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

Then, as @shikai ng noted, you will need to adjust your loop:然后,正如@shikai ng 指出的那样,您需要调整循环:

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

as Java arrays are 0 based.因为 Java 数组是基于 0 的。

You are having an array out of bound exception.您有一个数组越界异常。 just make sure you start ur for loop with i = 0 not i = 1只要确保你用 i = 0 而不是 i = 1 来启动你的 for 循环

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

and initialize bfparray only after getting the number of customers并且只有在获得客户数量后才初始化 bfparray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM