How to manipulate arrays. Find the average. Beginn

2019-01-11 14:59发布

I have a homework assignment and I was wondering if anyone could help me as I am new to Java and programming and am stuck on a question. The question is:

The first method finds the average of the elements of an integer array:

public double average(int[] data)

That is, given an integer array, data, calculate the average of its elements are return the average value. For example, the average of {1, 3, 2, 5, 8} is 3.8.

Here is what I have done so far:

public double average(int[] data) {  
    int sum = 0;

    while(int i=0; i < data.length; i++) 

    sum = sum + data[i]; 
    double average = sum / data.length;; 

    System.out.println("Average value of array element is " " + average);
}

When compiling it I get an error message at the int i=0 part saying '.class expected'. Any help would be appreciated.

8条回答
我想做一个坏孩纸
2楼-- · 2019-01-11 15:47

Using an enhanced for would be even nicer:

int sum = 0;
for (int d : data) sum += d;

Another thing that will probably give you a big surprise is the wrong result that you will obtain from

double average = sum / data.length;

Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length and only then promote that integer to a double. A solution would be

double average = 1.0d * sum / data.length;

This will force the dividend into a double, which will automatically propagate to the divisor.

查看更多
做个烂人
3楼-- · 2019-01-11 15:47

Couple of problems:

The while should be a for You are not returning a value but you have declared a return type of double

double average = sum / data.length;;

sum and data.length are both ints so the division will return an int - check your types

double semi-colon, probably won't break it, just looks odd.

查看更多
登录 后发表回答