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.
Best way to find the average of some numbers is trying Classes ......
The Java 8 streaming api offers an elegant alternative:
If we want to add numbers of an Array and find the average of them follow this easy way! .....
Well, to calculate the average of an array, you can consider using
for
loop instead of while loop.So as per your question let me assume an array as
arrNumbers
( here i'm considering the same array elements as in your question )You can use
scanner
class as well. It's left to you.Try this way
if you need to return average value you need to use double key word Instead of the void key word and need to return value return average.